effect-browserbase 0.2.0-beta.7 → 0.2.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -22
- package/dist/Account.mjs +3 -3
- package/dist/{Acquisition-Ca4EE-Fg.mjs → Acquisition-BOABu_qJ.mjs} +21 -12
- package/dist/Acquisition-BOABu_qJ.mjs.map +1 -0
- package/dist/Agents.mjs +25 -25
- package/dist/Agents.mjs.map +1 -1
- package/dist/Allocation.mjs +1 -1
- package/dist/{Browser-BPcF550A.mjs → Browser-ByrWJ0ss.mjs} +21 -17
- package/dist/Browser-ByrWJ0ss.mjs.map +1 -0
- package/dist/Browser.d.mts +11 -9
- package/dist/Browser.mjs +1 -1
- package/dist/Certificates.mjs +9 -9
- package/dist/Certificates.mjs.map +1 -1
- package/dist/{Client-4RMKIpL2.mjs → Client-BEC4Q8ZS.mjs} +154 -14
- package/dist/Client-BEC4Q8ZS.mjs.map +1 -0
- package/dist/Client.mjs +1 -1
- package/dist/ContextCoordination.mjs +9 -8
- package/dist/ContextCoordination.mjs.map +1 -1
- package/dist/Contexts.mjs +7 -7
- package/dist/Contexts.mjs.map +1 -1
- package/dist/Downloads.mjs +10 -10
- package/dist/Downloads.mjs.map +1 -1
- package/dist/{Extensions-Dg3jHOf0.mjs → Extensions-BTUn9zhK.mjs} +8 -8
- package/dist/Extensions-BTUn9zhK.mjs.map +1 -0
- package/dist/Extensions.mjs +1 -1
- package/dist/Functions.mjs +27 -27
- package/dist/Functions.mjs.map +1 -1
- package/dist/PageFetch.mjs +4 -4
- package/dist/PageFetch.mjs.map +1 -1
- package/dist/Projects.mjs +5 -5
- package/dist/Projects.mjs.map +1 -1
- package/dist/Recordings.mjs +42 -27
- package/dist/Recordings.mjs.map +1 -1
- package/dist/Replays.mjs +6 -6
- package/dist/Replays.mjs.map +1 -1
- package/dist/{Resource-DBksC4zB.mjs → Resource-J7Kkk5mu.mjs} +7 -3
- package/dist/Resource-J7Kkk5mu.mjs.map +1 -0
- package/dist/Search.mjs +4 -4
- package/dist/Search.mjs.map +1 -1
- package/dist/{Sessions-BUoyPcPJ.mjs → Sessions-D2H5m6rF.mjs} +15 -15
- package/dist/Sessions-D2H5m6rF.mjs.map +1 -0
- package/dist/Sessions.mjs +1 -1
- package/dist/Testing.mjs +1 -1
- package/dist/Uploads.mjs +4 -4
- package/dist/Uploads.mjs.map +1 -1
- package/dist/Webhooks.mjs +14 -14
- package/dist/Webhooks.mjs.map +1 -1
- package/package.json +3 -3
- package/dist/Acquisition-Ca4EE-Fg.mjs.map +0 -1
- package/dist/Browser-BPcF550A.mjs.map +0 -1
- package/dist/Client-4RMKIpL2.mjs.map +0 -1
- package/dist/Extensions-Dg3jHOf0.mjs.map +0 -1
- package/dist/Resource-DBksC4zB.mjs.map +0 -1
- package/dist/Sessions-BUoyPcPJ.mjs.map +0 -1
package/dist/Webhooks.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Webhooks.mjs","names":[],"sources":["../src/Webhooks.ts"],"sourcesContent":["import { Context, Effect, Layer, Redacted, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\nimport { Identifier } from \"./References.ts\";\n\nconst Timestamp = Schema.String.check(Schema.isMaxLength(64));\n\n/** Provider event names. Browserbase currently emits Functions events only. */\nexport const WebhookEventType = Schema.Literals([\n \"functions.builds.running\",\n \"functions.builds.completed\",\n \"functions.builds.failed\",\n \"functions.invocations.pending\",\n \"functions.invocations.running\",\n \"functions.invocations.completed\",\n \"functions.invocations.failed\",\n]);\n\nexport type WebhookEventType = typeof WebhookEventType.Type;\n\nconst Endpoint = Schema.NonEmptyString.check(\n Schema.isMaxLength(2048),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return url.protocol === \"https:\" && !url.username && !url.password;\n } catch {\n return false;\n }\n }),\n);\n\nconst EventTypes = Schema.Array(WebhookEventType).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(7),\n Schema.isUnique(),\n);\n\nexport const WebhookSettings = Schema.Struct({ endpoint: Endpoint, eventTypes: EventTypes });\nexport type WebhookSettings = typeof WebhookSettings.Type;\n\nexport const WebhookUpdate = Schema.Struct({\n endpoint: Schema.optionalKey(Endpoint),\n eventTypes: Schema.optionalKey(EventTypes),\n});\n\nexport type WebhookUpdate = typeof WebhookUpdate.Type;\n\nexport class WebhookMetadata extends Schema.Class<WebhookMetadata>(\"BrowserbaseWebhookMetadata\")({\n webhookId: Identifier,\n projectId: Identifier,\n endpoint: Schema.String.check(Schema.isMaxLength(2048)),\n eventTypes: Schema.Array(Schema.String.check(Schema.isMaxLength(128))).check(\n Schema.isMaxLength(64),\n ),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\n/** A signing secret is returned once, redacted so it cannot be logged by accident. */\nexport interface WebhookRegistration {\n readonly webhook: WebhookMetadata;\n readonly secret: Redacted.Redacted<string>;\n}\n\nexport interface WebhookPage {\n readonly webhooks: ReadonlyArray<WebhookMetadata>;\n readonly nextCursor: string | undefined;\n}\n\nconst ProviderWebhook = Schema.Struct({\n id: Identifier,\n projectId: Identifier,\n endpoint: WebhookMetadata.fields.endpoint,\n eventTypes: WebhookMetadata.fields.eventTypes,\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\n\nconst Secret = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\n\nconst Page = Schema.Struct({\n data: Schema.Array(ProviderWebhook).check(Schema.isMaxLength(100)),\n nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n});\n\nexport const WebhookListQuery = Schema.Struct({\n cursor: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(4096))),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n});\n\nexport type WebhookListQuery = typeof WebhookListQuery.Type;\n\n/** Webhook administration for the Client's project. Mutations are never retried. */\nexport class BrowserbaseWebhooks extends Context.Service<\n BrowserbaseWebhooks,\n {\n readonly create: (\n settings: WebhookSettings,\n ) => Effect.Effect<WebhookRegistration, PlatformError>;\n readonly list: (query?: WebhookListQuery) => Effect.Effect<WebhookPage, PlatformError>;\n readonly retrieve: (webhookId: string) => Effect.Effect<WebhookMetadata, PlatformError>;\n readonly update: (\n webhookId: string,\n update: WebhookUpdate,\n ) => Effect.Effect<WebhookMetadata, PlatformError>;\n readonly delete: (webhookId: string) => Effect.Effect<void, PlatformError>;\n /** Issues a new secret; the old one keeps working unless `revokeImmediately`. */\n readonly rotateSecret: (\n webhookId: string,\n options?: { readonly revokeImmediately?: boolean },\n ) => Effect.Effect<Redacted.Redacted<string>, PlatformError>;\n }\n>()(\"effect-browserbase/Webhooks\") {\n static readonly layer: Layer.Layer<BrowserbaseWebhooks, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseWebhooks,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const api = resource<PlatformError>(client, (failure) =>\n PlatformError.make({ ...failure, service: \"webhooks\" }),\n );\n\n const decode = (\n operation: PlatformError[\"operation\"],\n mutation: boolean,\n expected?: string,\n ) =>\n Effect.fnUntraced(function* (value: typeof ProviderWebhook.Type) {\n if (\n value.projectId !== client.projectId ||\n (expected !== undefined && value.id !== expected)\n )\n return yield* api.malformed(operation, mutation);\n\n const { id, ...rest } = value;\n\n return WebhookMetadata.make({ webhookId: id, ...rest });\n });\n\n const path = (id: string) => `/v1/webhooks/${api.segment(id)}`;\n\n const create = Effect.fn(\"BrowserbaseWebhooks.create\")(function* (settings: WebhookSettings) {\n const value = yield* api.input(WebhookSettings, settings, \"webhook-create\");\n\n const created = yield* api.request(\n \"POST\",\n \"/v1/webhooks\",\n Schema.Struct({ ...ProviderWebhook.fields, secret: Secret }),\n \"webhook-create\",\n value,\n );\n\n const { secret, ...webhook } = created;\n\n return {\n webhook: yield* decode(\"webhook-create\", true)(webhook),\n secret: Redacted.make(secret),\n };\n });\n\n const list = Effect.fn(\"BrowserbaseWebhooks.list\")(function* (query: WebhookListQuery = {}) {\n const value = yield* api.input(WebhookListQuery, query, \"webhook-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/webhooks${api.query(value)}`,\n Page,\n \"webhook-list\",\n );\n\n return {\n webhooks: yield* Effect.forEach(page.data, decode(\"webhook-list\", false)),\n nextCursor: page.nextCursor ?? undefined,\n };\n });\n\n const retrieve = Effect.fn(\"BrowserbaseWebhooks.retrieve\")(function* (webhookId: string) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-retrieve\");\n const value = yield* api.request(\"GET\", path(id), ProviderWebhook, \"webhook-retrieve\");\n\n return yield* decode(\"webhook-retrieve\", false, id)(value);\n });\n\n const update = Effect.fn(\"BrowserbaseWebhooks.update\")(function* (\n webhookId: string,\n changes: WebhookUpdate,\n ) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-update\");\n const value = yield* api.input(WebhookUpdate, changes, \"webhook-update\");\n\n if (value.endpoint === undefined && value.eventTypes === undefined)\n return yield* api.configuration(\"webhook-update\");\n\n const updated = yield* api.request(\n \"PATCH\",\n path(id),\n ProviderWebhook,\n \"webhook-update\",\n value,\n );\n\n return yield* decode(\"webhook-update\", true, id)(updated);\n });\n\n const remove = Effect.fn(\"BrowserbaseWebhooks.delete\")(function* (webhookId: string) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-delete\");\n\n yield* api.remove(path(id), \"webhook-delete\");\n });\n\n const rotateSecret = Effect.fn(\"BrowserbaseWebhooks.rotateSecret\")(function* (\n webhookId: string,\n options: { readonly revokeImmediately?: boolean } = {},\n ) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-rotate-secret\");\n\n const value = yield* api.input(\n Schema.Struct({ revokeImmediately: Schema.optionalKey(Schema.Boolean) }),\n options,\n \"webhook-rotate-secret\",\n );\n\n const rotated = yield* api.request(\n \"POST\",\n `${path(id)}/secret`,\n Schema.Struct({ secret: Secret }),\n \"webhook-rotate-secret\",\n value,\n );\n\n return Redacted.make(rotated.secret);\n });\n\n return BrowserbaseWebhooks.of({\n create,\n list,\n retrieve,\n update,\n delete: remove,\n rotateSecret,\n });\n }),\n );\n}\n"],"mappings":";;;;;;AAOA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;;AAG5D,MAAa,mBAAmB,OAAO,SAAS;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,WAAW,OAAO,eAAe,MACrC,OAAO,YAAY,IAAI,GACvB,OAAO,YAAY,UAAU;CAC3B,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EAEzB,OAAO,IAAI,aAAa,YAAY,CAAC,IAAI,YAAY,CAAC,IAAI;CAC5D,QAAQ;EACN,OAAO;CACT;AACF,CAAC,CACH;AAEA,MAAM,aAAa,OAAO,MAAM,gBAAgB,CAAC,CAAC,MAChD,OAAO,YAAY,CAAC,GACpB,OAAO,YAAY,CAAC,GACpB,OAAO,SAAS,CAClB;AAEA,MAAa,kBAAkB,OAAO,OAAO;CAAE,UAAU;CAAU,YAAY;AAAW,CAAC;AAG3F,MAAa,gBAAgB,OAAO,OAAO;CACzC,UAAU,OAAO,YAAY,QAAQ;CACrC,YAAY,OAAO,YAAY,UAAU;AAC3C,CAAC;AAID,IAAa,kBAAb,cAAqC,OAAO,MAAuB,4BAA4B,CAAC,CAAC;CAC/F,WAAW;CACX,WAAW;CACX,UAAU,OAAO,OAAO,MAAM,OAAO,YAAY,IAAI,CAAC;CACtD,YAAY,OAAO,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC,CAAC,CAAC,MACrE,OAAO,YAAY,EAAE,CACvB;CACA,WAAW;CACX,WAAW;AACb,CAAC,CAAC,CAAC,CAAC;AAaJ,MAAM,kBAAkB,OAAO,OAAO;CACpC,IAAI;CACJ,WAAW;CACX,UAAU,gBAAgB,OAAO;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AAE,GACP,iBACA,kBACA,KACF;GAEA,OAAO,OAAO,OAAO,kBAAkB,MAAM,EAAE,CAAC,CAAC,OAAO;EAC1D,CAAC;EAED,MAAM,SAAS,OAAO,GAAG,4BAA4B,CAAC,CAAC,WAAW,WAAmB;GACnF,MAAM,KAAK,OAAO,IAAI,MAAM,YAAY,WAAW,gBAAgB;GAEnE,OAAO,IAAI,OAAO,KAAK,EAAE,GAAG,gBAAgB;EAC9C,CAAC;EAED,MAAM,eAAe,OAAO,GAAG,kCAAkC,CAAC,CAAC,WACjE,WACA,UAAoD,CAAC,GACrD;GACA,MAAM,KAAK,OAAO,IAAI,MAAM,YAAY,WAAW,uBAAuB;GAE1E,MAAM,QAAQ,OAAO,IAAI,MACvB,OAAO,OAAO,EAAE,mBAAmB,OAAO,YAAY,OAAO,OAAO,EAAE,CAAC,GACvE,SACA,uBACF;GAEA,MAAM,UAAU,OAAO,IAAI,QACzB,QACA,GAAG,KAAK,EAAE,EAAE,UACZ,OAAO,OAAO,EAAE,QAAQ,OAAO,CAAC,GAChC,yBACA,KACF;GAEA,OAAO,SAAS,KAAK,QAAQ,MAAM;EACrC,CAAC;EAED,OAAO,oBAAoB,GAAG;GAC5B;GACA;GACA;GACA;GACA,QAAQ;GACR;EACF,CAAC;CACH,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"Webhooks.mjs","names":["Trace.span"],"sources":["../src/Webhooks.ts"],"sourcesContent":["import { Context, Effect, Layer, Redacted, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { PlatformError } from \"./Errors.ts\";\nimport { resource } from \"./internal/http/Resource.ts\";\nimport * as Trace from \"./internal/Trace.ts\";\nimport { Identifier } from \"./References.ts\";\n\nconst Timestamp = Schema.String.check(Schema.isMaxLength(64));\n\n/** Provider event names. Browserbase currently emits Functions events only. */\nexport const WebhookEventType = Schema.Literals([\n \"functions.builds.running\",\n \"functions.builds.completed\",\n \"functions.builds.failed\",\n \"functions.invocations.pending\",\n \"functions.invocations.running\",\n \"functions.invocations.completed\",\n \"functions.invocations.failed\",\n]);\n\nexport type WebhookEventType = typeof WebhookEventType.Type;\n\nconst Endpoint = Schema.NonEmptyString.check(\n Schema.isMaxLength(2048),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return url.protocol === \"https:\" && !url.username && !url.password;\n } catch {\n return false;\n }\n }),\n);\n\nconst EventTypes = Schema.Array(WebhookEventType).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(7),\n Schema.isUnique(),\n);\n\nexport const WebhookSettings = Schema.Struct({ endpoint: Endpoint, eventTypes: EventTypes });\nexport type WebhookSettings = typeof WebhookSettings.Type;\n\nexport const WebhookUpdate = Schema.Struct({\n endpoint: Schema.optionalKey(Endpoint),\n eventTypes: Schema.optionalKey(EventTypes),\n});\n\nexport type WebhookUpdate = typeof WebhookUpdate.Type;\n\nexport class WebhookMetadata extends Schema.Class<WebhookMetadata>(\"BrowserbaseWebhookMetadata\")({\n webhookId: Identifier,\n projectId: Identifier,\n endpoint: Schema.String.check(Schema.isMaxLength(2048)),\n eventTypes: Schema.Array(Schema.String.check(Schema.isMaxLength(128))).check(\n Schema.isMaxLength(64),\n ),\n createdAt: Timestamp,\n updatedAt: Timestamp,\n}) {}\n\n/** A signing secret is returned once, redacted so it cannot be logged by accident. */\nexport interface WebhookRegistration {\n readonly webhook: WebhookMetadata;\n readonly secret: Redacted.Redacted<string>;\n}\n\nexport interface WebhookPage {\n readonly webhooks: ReadonlyArray<WebhookMetadata>;\n readonly nextCursor: string | undefined;\n}\n\nconst ProviderWebhook = Schema.Struct({\n id: Identifier,\n projectId: Identifier,\n endpoint: WebhookMetadata.fields.endpoint,\n eventTypes: WebhookMetadata.fields.eventTypes,\n createdAt: Timestamp,\n updatedAt: Timestamp,\n});\n\nconst Secret = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\n\nconst Page = Schema.Struct({\n data: Schema.Array(ProviderWebhook).check(Schema.isMaxLength(100)),\n nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096)))),\n});\n\nexport const WebhookListQuery = Schema.Struct({\n cursor: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(4096))),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n});\n\nexport type WebhookListQuery = typeof WebhookListQuery.Type;\n\n/** Webhook administration for the Client's project. Mutations are never retried. */\nexport class BrowserbaseWebhooks extends Context.Service<\n BrowserbaseWebhooks,\n {\n readonly create: (\n settings: WebhookSettings,\n ) => Effect.Effect<WebhookRegistration, PlatformError>;\n readonly list: (query?: WebhookListQuery) => Effect.Effect<WebhookPage, PlatformError>;\n readonly retrieve: (webhookId: string) => Effect.Effect<WebhookMetadata, PlatformError>;\n readonly update: (\n webhookId: string,\n update: WebhookUpdate,\n ) => Effect.Effect<WebhookMetadata, PlatformError>;\n readonly delete: (webhookId: string) => Effect.Effect<void, PlatformError>;\n /** Issues a new secret; the old one keeps working unless `revokeImmediately`. */\n readonly rotateSecret: (\n webhookId: string,\n options?: { readonly revokeImmediately?: boolean },\n ) => Effect.Effect<Redacted.Redacted<string>, PlatformError>;\n }\n>()(\"effect-browserbase/Webhooks\") {\n static readonly layer: Layer.Layer<BrowserbaseWebhooks, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseWebhooks,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const api = resource<PlatformError>(client, (failure) =>\n PlatformError.make({ ...failure, service: \"webhooks\" }),\n );\n\n const decode = (\n operation: PlatformError[\"operation\"],\n mutation: boolean,\n expected?: string,\n ) =>\n Effect.fnUntraced(function* (value: typeof ProviderWebhook.Type) {\n if (\n value.projectId !== client.projectId ||\n (expected !== undefined && value.id !== expected)\n )\n return yield* api.malformed(operation, mutation);\n\n const { id, ...rest } = value;\n\n return WebhookMetadata.make({ webhookId: id, ...rest });\n });\n\n const path = (id: string) => `/v1/webhooks/${api.segment(id)}`;\n\n const create = Effect.fnUntraced(function* (settings: WebhookSettings) {\n const value = yield* api.input(WebhookSettings, settings, \"webhook-create\");\n\n const created = yield* api.request(\n \"POST\",\n \"/v1/webhooks\",\n Schema.Struct({ ...ProviderWebhook.fields, secret: Secret }),\n \"webhook-create\",\n value,\n );\n\n const { secret, ...webhook } = created;\n\n return {\n webhook: yield* decode(\"webhook-create\", true)(webhook),\n secret: Redacted.make(secret),\n };\n }, Trace.span(\"BrowserbaseWebhooks.create\"));\n\n const list = Effect.fnUntraced(function* (query: WebhookListQuery = {}) {\n const value = yield* api.input(WebhookListQuery, query, \"webhook-list\");\n\n const page = yield* api.request(\n \"GET\",\n `/v1/webhooks${api.query(value)}`,\n Page,\n \"webhook-list\",\n );\n\n return {\n webhooks: yield* Effect.forEach(page.data, decode(\"webhook-list\", false)),\n nextCursor: page.nextCursor ?? undefined,\n };\n }, Trace.span(\"BrowserbaseWebhooks.list\"));\n\n const retrieve = Effect.fnUntraced(function* (webhookId: string) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-retrieve\");\n const value = yield* api.request(\"GET\", path(id), ProviderWebhook, \"webhook-retrieve\");\n\n return yield* decode(\"webhook-retrieve\", false, id)(value);\n }, Trace.span(\"BrowserbaseWebhooks.retrieve\"));\n\n const update = Effect.fnUntraced(function* (webhookId: string, changes: WebhookUpdate) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-update\");\n const value = yield* api.input(WebhookUpdate, changes, \"webhook-update\");\n\n if (value.endpoint === undefined && value.eventTypes === undefined)\n return yield* api.configuration(\"webhook-update\");\n\n const updated = yield* api.request(\n \"PATCH\",\n path(id),\n ProviderWebhook,\n \"webhook-update\",\n value,\n );\n\n return yield* decode(\"webhook-update\", true, id)(updated);\n }, Trace.span(\"BrowserbaseWebhooks.update\"));\n\n const remove = Effect.fnUntraced(function* (webhookId: string) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-delete\");\n\n yield* api.remove(path(id), \"webhook-delete\");\n }, Trace.span(\"BrowserbaseWebhooks.delete\"));\n\n const rotateSecret = Effect.fnUntraced(function* (\n webhookId: string,\n options: { readonly revokeImmediately?: boolean } = {},\n ) {\n const id = yield* api.input(Identifier, webhookId, \"webhook-rotate-secret\");\n\n const value = yield* api.input(\n Schema.Struct({ revokeImmediately: Schema.optionalKey(Schema.Boolean) }),\n options,\n \"webhook-rotate-secret\",\n );\n\n const rotated = yield* api.request(\n \"POST\",\n `${path(id)}/secret`,\n Schema.Struct({ secret: Secret }),\n \"webhook-rotate-secret\",\n value,\n );\n\n return Redacted.make(rotated.secret);\n }, Trace.span(\"BrowserbaseWebhooks.rotateSecret\"));\n\n return BrowserbaseWebhooks.of({\n create,\n list,\n retrieve,\n update,\n delete: remove,\n rotateSecret,\n });\n }),\n );\n}\n"],"mappings":";;;;;;AAQA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;;AAG5D,MAAa,mBAAmB,OAAO,SAAS;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,WAAW,OAAO,eAAe,MACrC,OAAO,YAAY,IAAI,GACvB,OAAO,YAAY,UAAU;CAC3B,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EAEzB,OAAO,IAAI,aAAa,YAAY,CAAC,IAAI,YAAY,CAAC,IAAI;CAC5D,QAAQ;EACN,OAAO;CACT;AACF,CAAC,CACH;AAEA,MAAM,aAAa,OAAO,MAAM,gBAAgB,CAAC,CAAC,MAChD,OAAO,YAAY,CAAC,GACpB,OAAO,YAAY,CAAC,GACpB,OAAO,SAAS,CAClB;AAEA,MAAa,kBAAkB,OAAO,OAAO;CAAE,UAAU;CAAU,YAAY;AAAW,CAAC;AAG3F,MAAa,gBAAgB,OAAO,OAAO;CACzC,UAAU,OAAO,YAAY,QAAQ;CACrC,YAAY,OAAO,YAAY,UAAU;AAC3C,CAAC;AAID,IAAa,kBAAb,cAAqC,OAAO,MAAuB,4BAA4B,CAAC,CAAC;CAC/F,WAAW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",
|
|
3
|
-
"version": "0.2.0-beta.
|
|
3
|
+
"version": "0.2.0-beta.9",
|
|
4
4
|
"description": "Effect-based Browserbase resources and hosted integration for effect-browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
"node": "^22.18.0 || >=24.11.0"
|
|
15
15
|
},
|
|
16
16
|
"peerDependencies": {
|
|
17
|
-
"effect": "
|
|
18
|
-
"effect-browser": "0.2.0-beta.
|
|
17
|
+
"effect": "4.0.0-rc.117",
|
|
18
|
+
"effect-browser": "0.2.0-beta.9"
|
|
19
19
|
},
|
|
20
20
|
"homepage": "https://github.com/mannyc2/effect-agent-browserbase#readme",
|
|
21
21
|
"bugs": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Acquisition-Ca4EE-Fg.mjs","names":[],"sources":["../src/internal/session/Cleanup.ts","../src/internal/session/Diagnostics.ts","../src/internal/session/Acquisition.ts"],"sourcesContent":["import { Effect, Option } from \"effect\";\nimport { cleanupStep, noConnection, type ConnectionCleanup } from \"effect-browser/browser-runtime\";\n\nexport { reported } from \"effect-browser/browser-runtime\";\nexport type { ConnectionCleanup as LocalCleanup } from \"effect-browser/browser-runtime\";\n\nimport { CleanupIssue, CleanupResult } from \"../../Cleanup.ts\";\nimport type { SessionReference } from \"../../References.ts\";\nimport type { SessionStatus } from \"../../SessionData.ts\";\nimport type { BrowserbaseSessions } from \"../../Sessions.ts\";\n\nexport const noLocalConnection = noConnection;\n\n/** Internal limits, also injectable by deterministic failure tests. */\nexport interface CleanupLimits {\n readonly localStepMillis: number;\n readonly releaseMillis: number;\n readonly terminalMillis: number;\n}\n\nexport const defaultCleanupLimits: CleanupLimits = {\n localStepMillis: 3000,\n releaseMillis: 4000,\n terminalMillis: 4000,\n};\n\n/**\n * Close is one uninterruptible, bounded transaction over *local cleanup evidence*, not\n * a transaction over the remote browser. Each step observes its own Exit so failures\n * cannot suppress a later disconnect, release request, or exact-session status read.\n */\nexport const makeCleanup = Effect.fnUntraced(function* (\n reference: SessionReference,\n ownership: CleanupResult[\"ownership\"],\n sessions: BrowserbaseSessions[\"Service\"],\n local: ConnectionCleanup,\n report: (result: CleanupResult) => void,\n limits: CleanupLimits = defaultCleanupLimits,\n) {\n let latest: CleanupResult | undefined;\n\n const close = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const issues: CleanupIssue[] = [];\n\n const step = <A, E>(\n name: CleanupIssue[\"step\"],\n action: Effect.Effect<A, E>,\n milliseconds: number,\n ) =>\n cleanupStep(action, milliseconds).pipe(\n Effect.tap((result) =>\n Effect.sync(() => {\n if (result._tag === \"Failure\")\n issues.push(CleanupIssue.make({ step: name, reason: result.reason }));\n }),\n ),\n );\n\n // The fence runs synchronously before interruptible native teardown begins.\n yield* step(\"fence\", local.fence, limits.localStepMillis);\n yield* step(\"capture\", local.capture, limits.localStepMillis);\n yield* step(\"initialization\", local.initialization, limits.localStepMillis);\n const disconnected = yield* step(\"disconnect\", local.disconnect, limits.localStepMillis);\n const localState = disconnected._tag === \"Success\" ? disconnected.value : \"failed\";\n\n let releaseRequested = false;\n let remote: CleanupResult[\"remote\"] = ownership === \"borrowed\" ? \"not-owned\" : \"unknown\";\n let observedStatus: SessionStatus | undefined;\n\n if (ownership === \"owned\") {\n const requested = yield* step(\n \"release\",\n sessions.requestRelease(reference),\n limits.releaseMillis,\n );\n\n releaseRequested = requested._tag === \"Success\";\n\n // A POST response is never substituted for a passive terminal-state observation.\n const terminal = yield* step(\n \"status\",\n sessions.waitForTerminal(reference, { timeoutMillis: limits.terminalMillis }),\n limits.terminalMillis,\n );\n\n if (terminal._tag === \"Success\") {\n remote = \"confirmed\";\n observedStatus = terminal.value.status;\n } else if (requested._tag === \"Success\") {\n remote = \"pending\";\n }\n }\n\n const result = CleanupResult.make({\n reference,\n ownership,\n releaseRequested,\n remote,\n local: localState,\n ...(observedStatus === undefined ? {} : { observedStatus }),\n issues,\n });\n\n Object.freeze(result.issues);\n latest = Object.freeze(result);\n report(latest);\n\n return latest;\n }),\n ),\n );\n\n return {\n close,\n result: Effect.sync(() => Option.fromNullishOr(latest)),\n };\n});\n","import { Cause, Data, Effect, ErrorReporter } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport type { AllocationAttempt } from \"../../References.ts\";\n\n/**\n * Operator-visible evidence that a session's fate was not settled. It carries identity and\n * outcome labels only: no provider body, connection URL, credential or page content. The\n * transport deliberately disables tracing where credentials travel, so without this an\n * unconfirmed release or an allocation of unknown outcome would leave no trace for anyone who\n * did not register a callback.\n */\nclass SessionUnsettled extends Data.TaggedError(\"BrowserbaseSessionUnsettled\")<{\n readonly message: string;\n readonly details: Readonly<Record<string, string | number>>;\n}> {\n override readonly [ErrorReporter.severity] = \"Warn\" as const;\n\n override get [ErrorReporter.attributes]() {\n return this.details;\n }\n}\n\nconst surface = (message: string, details: Readonly<Record<string, string | number>>) =>\n Effect.logWarning(message).pipe(\n Effect.annotateLogs(details),\n Effect.andThen(ErrorReporter.report(Cause.fail(new SessionUnsettled({ message, details })))),\n );\n\n/** A borrowed scope never owns release, so only its local teardown can be unsettled. */\nexport const reportCleanup = (result: CleanupResult): Effect.Effect<void> => {\n const remoteUnsettled =\n result.ownership === \"owned\" && (result.remote !== \"confirmed\" || !result.releaseRequested);\n\n if (!remoteUnsettled && result.local !== \"failed\" && result.issues.length === 0)\n return Effect.void;\n\n return surface(\"Browserbase session cleanup ended without confirmation\", {\n projectId: result.reference.projectId,\n sessionId: result.reference.sessionId,\n ownership: result.ownership,\n remote: result.remote,\n local: result.local,\n observedStatus: result.observedStatus ?? \"unobserved\",\n issues: result.issues.map((issue) => `${issue.step}:${issue.reason}`).join(\",\") || \"none\",\n });\n};\n\n/** The provider may have allocated a session this process has no reference for. */\nexport const reportAllocationUncertain = (attempt: AllocationAttempt): Effect.Effect<void> =>\n surface(\"Browserbase allocation outcome is unknown\", {\n projectId: attempt.projectId,\n attemptId: attempt.attemptId,\n requestedAtMillis: attempt.requestedAtMillis,\n });\n","import { Clock, Crypto, Effect, Exit, Option, Schema, Scope } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport { AllocationError, ContextError, type ClientError, SessionError } from \"../../Errors.ts\";\nimport type { LaunchRecipe } from \"../../Launch.ts\";\nimport { type AllocationAttempt, Identifier, SessionReference } from \"../../References.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { connectionAddress } from \"../provider/Connection.ts\";\nimport { compileLaunch } from \"../provider/Launch.ts\";\nimport {\n makeCleanup,\n noLocalConnection,\n reported,\n type CleanupLimits,\n type LocalCleanup,\n} from \"./Cleanup.ts\";\nimport { requireContextWriterPermit, type ContextWriterPermitInternal } from \"./ContextWriter.ts\";\nimport { reportAllocationUncertain, reportCleanup } from \"./Diagnostics.ts\";\nimport type { ContextWriterPermit } from \"./WriterFacts.ts\";\n\nconst AllocatedIdentity = Schema.Struct({ id: Identifier, projectId: Identifier });\n\nexport interface AcquisitionOptions {\n readonly launch: LaunchRecipe;\n readonly contextWriter?: ContextWriterPermit;\n readonly allocationDeadline?: number;\n /** Bounded host notification of the canonical facts. Reporting never changes them. */\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n /** Exactly one notification when a creation attempt's effect on the provider is unknown. */\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\n/**\n * The remote lease is registered before POST. Local connection work is supplied by\n * the same browser owner; the control plane never invents a second operation owner.\n */\nexport const acquireRemote = Effect.fnUntraced(function* (\n options: AcquisitionOptions,\n local: LocalCleanup = noLocalConnection,\n limits?: CleanupLimits,\n) {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const crypto = yield* Crypto.Crypto;\n const parent = yield* Scope.Scope;\n\n const launch = yield* compileLaunch(options.launch, {\n projectId: client.projectId,\n // Secure randomness is a platform precondition, so its failure is a defect, not an outcome.\n attemptId: yield* Effect.orDie(crypto.randomUUIDv4),\n requestedAtMillis: yield* Clock.currentTimeMillis,\n });\n\n const attempt = launch.attempt;\n let writer: ContextWriterPermitInternal | undefined;\n\n if (launch.context?.persist) {\n if (options.contextWriter === undefined) {\n return yield* ContextError.make({\n operation: \"writer-authority\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n }\n writer = yield* requireContextWriterPermit(options.contextWriter, {\n provider: \"browserbase\",\n projectId: client.projectId,\n contextId: launch.context.id,\n });\n } else if (options.contextWriter !== undefined) {\n return yield* ContextError.make({\n operation: \"writer-authority\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n }\n\n return yield* Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const resourceScope = yield* Scope.make();\n let reference: SessionReference | undefined;\n let admitted = false;\n let knownRejection = false;\n let closing = false;\n let cleanup: CleanupResult | undefined;\n\n let uncertainReported = false;\n\n const allocationUncertain = Effect.suspend(() => {\n if (uncertainReported) return Effect.void;\n uncertainReported = true;\n\n return reportAllocationUncertain(attempt).pipe(\n Effect.andThen(\n options.onAllocationUncertain === undefined\n ? Effect.void\n : reported(options.onAllocationUncertain(attempt)),\n ),\n );\n });\n\n const terminate = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n closing = true;\n if (reference === undefined) {\n if (admitted && !knownRejection) {\n writer?.uncertain(attempt);\n yield* allocationUncertain;\n }\n\n return;\n }\n\n const coordinator = yield* makeCleanup(\n reference,\n \"owned\",\n sessions,\n local,\n (result) => {\n cleanup = result;\n writer?.completed(attempt, result);\n },\n limits,\n );\n\n yield* coordinator.close;\n const result = cleanup;\n const notify = options.onCleanup;\n\n if (result !== undefined) {\n yield* reported(Effect.suspend(() => reportCleanup(result)));\n if (notify !== undefined) yield* reported(Effect.suspend(() => notify(result)));\n }\n }),\n ),\n );\n\n const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));\n\n yield* Scope.addFinalizer(resourceScope, terminate);\n yield* Scope.addFinalizer(parent, closeScope);\n\n const failedAllocation = (error: ClientError): AllocationError => {\n knownRejection = error.outcome === \"rejected\" || error.outcome === \"undispatched\";\n if (knownRejection) writer?.rejected(attempt);\n else writer?.uncertain(attempt);\n const reason = error.reason;\n\n return AllocationError.make({\n attempt,\n outcome: knownRejection ? \"rejected\" : \"unknown\",\n reason:\n reason === \"authorization\" ||\n reason === \"rate-limited\" ||\n reason === \"configuration\" ||\n reason === \"transport\" ||\n reason === \"timeout\" ||\n reason === \"malformed\"\n ? reason\n : \"provider\",\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined\n ? {}\n : { retryAfterMillis: error.retryAfterMillis }),\n });\n };\n\n const allocate = Effect.gen(function* () {\n if (writer !== undefined) yield* writer.recordAttempt(attempt);\n admitted = true;\n\n const raw = yield* restore(\n client.json(\"POST\", \"/v1/sessions\", launch.body, options.allocationDeadline),\n ).pipe(Effect.mapError(failedAllocation));\n\n const identity = yield* Schema.decodeUnknownEffect(AllocatedIdentity)(raw).pipe(\n Effect.mapError(() =>\n AllocationError.make({ attempt, outcome: \"unknown\", reason: \"malformed\" }),\n ),\n );\n\n // Save identity before interpreting any connection credentials or provider metadata.\n reference = Object.freeze(\n SessionReference.make({\n provider: \"browserbase\",\n projectId: identity.projectId,\n sessionId: identity.id,\n }),\n );\n writer?.recordSession(attempt, reference);\n if (reference.projectId !== client.projectId) {\n return yield* AllocationError.make({\n attempt,\n reference,\n outcome: \"unknown\",\n reason: \"malformed\",\n });\n }\n const ref = reference;\n\n return {\n reference: ref,\n attempt,\n launch,\n resourceScope,\n isClosed: () => closing,\n connection: (timeoutMillis: number) =>\n Effect.suspend(() =>\n closing\n ? Effect.fail(\n SessionError.make({\n operation: \"session-connect\",\n reason: \"expired\",\n outcome: \"undispatched\",\n }),\n )\n : connectionAddress(client, sessions, ref, timeoutMillis),\n ),\n release: closeScope.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n cleanup === undefined\n ? Effect.die(new Error(\"Owned session closed without cleanup evidence\"))\n : Effect.succeed(cleanup),\n ),\n ),\n ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n });\n\n return yield* allocate.pipe(\n Effect.onError(() => closeScope),\n Effect.onInterrupt(() => closeScope),\n );\n }),\n );\n});\n\nexport type RemoteAcquisition = Effect.Success<ReturnType<typeof acquireRemote>>;\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,oBAAoB;AASjC,MAAa,uBAAsC;CACjD,iBAAiB;CACjB,eAAe;CACf,gBAAgB;AAClB;;;;;;AAOA,MAAa,cAAc,OAAO,WAAW,WAC3C,WACA,WACA,UACA,OACA,QACA,SAAwB,sBACxB;CACA,IAAI;CA2EJ,OAAO;EACL,OAAA,OA1EmB,OAAO,OAC1B,OAAO,gBACL,OAAO,IAAI,aAAa;GACtB,MAAM,SAAyB,CAAC;GAEhC,MAAM,QACJ,MACA,QACA,iBAEA,YAAY,QAAQ,YAAY,CAAC,CAAC,KAChC,OAAO,KAAK,WACV,OAAO,WAAW;IAChB,IAAI,OAAO,SAAS,WAClB,OAAO,KAAK,aAAa,KAAK;KAAE,MAAM;KAAM,QAAQ,OAAO;IAAO,CAAC,CAAC;GACxE,CAAC,CACH,CACF;GAGF,OAAO,KAAK,SAAS,MAAM,OAAO,OAAO,eAAe;GACxD,OAAO,KAAK,WAAW,MAAM,SAAS,OAAO,eAAe;GAC5D,OAAO,KAAK,kBAAkB,MAAM,gBAAgB,OAAO,eAAe;GAC1E,MAAM,eAAe,OAAO,KAAK,cAAc,MAAM,YAAY,OAAO,eAAe;GACvF,MAAM,aAAa,aAAa,SAAS,YAAY,aAAa,QAAQ;GAE1E,IAAI,mBAAmB;GACvB,IAAI,SAAkC,cAAc,aAAa,cAAc;GAC/E,IAAI;GAEJ,IAAI,cAAc,SAAS;IACzB,MAAM,YAAY,OAAO,KACvB,WACA,SAAS,eAAe,SAAS,GACjC,OAAO,aACT;IAEA,mBAAmB,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,CAAC,KACrB,OAAO,cAAc,UAAU,GAC/B,OAAO,kBAAkB,UAAU,CACrC;CACF,CAAC,CACH;AACF,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Browser-BPcF550A.mjs","names":[],"sources":["../src/internal/session/Attachment.ts","../src/internal/session/Browser.ts","../src/Browser.ts"],"sourcesContent":["import { Effect, Exit, Option, Scope } from \"effect\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport { SessionError } from \"../../Errors.ts\";\nimport type { SessionReference } from \"../../References.ts\";\nimport { isTerminalSessionStatus } from \"../../SessionData.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { connectionAddress } from \"../provider/Connection.ts\";\nimport {\n makeCleanup,\n noLocalConnection,\n reported,\n type CleanupLimits,\n type LocalCleanup,\n} from \"./Cleanup.ts\";\nimport { reportCleanup } from \"./Diagnostics.ts\";\n\nexport interface AttachmentOptions {\n readonly reference: SessionReference;\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n}\n\nconst failure = (reason: SessionError[\"reason\"]) =>\n SessionError.make({ operation: \"session-attach\", reason, outcome: \"undispatched\" });\n\n/**\n * Borrowing an already running session. This scope owns its local connection and nothing\n * else: no allocation attempt is made, no release is requested, and no Context-writer\n * authority is claimed. Whoever allocated the session keeps all three.\n */\nexport const attachRemote = Effect.fnUntraced(function* (\n options: AttachmentOptions,\n local: LocalCleanup = noLocalConnection,\n limits?: CleanupLimits,\n) {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const parent = yield* Scope.Scope;\n const pendingWaitMillis = options.pendingWaitMillis ?? 0;\n\n if (\n !Number.isSafeInteger(pendingWaitMillis) ||\n pendingWaitMillis < 0 ||\n pendingWaitMillis > 600_000\n )\n return yield* failure(\"configuration\");\n\n // The status read validates project authority before anything is borrowed. A terminal\n // session needs a fresh allocation from durable state, never a reattachment.\n const observed = yield* sessions.retrieve(options.reference);\n\n if (isTerminalSessionStatus(observed.status)) return yield* failure(\"expired\");\n if (observed.status !== \"RUNNING\") {\n if (pendingWaitMillis === 0) return yield* failure(\"active\");\n yield* sessions.waitUntilRunning(observed.reference, { timeoutMillis: pendingWaitMillis });\n }\n const reference = observed.reference;\n\n return yield* Effect.uninterruptible(\n Effect.gen(function* () {\n const resourceScope = yield* Scope.make();\n let closing = false;\n let cleanup: CleanupResult | undefined;\n\n const terminate = yield* Effect.cached(\n Effect.uninterruptible(\n Effect.gen(function* () {\n closing = true;\n\n const coordinator = yield* makeCleanup(\n reference,\n \"borrowed\",\n sessions,\n local,\n (result) => {\n cleanup = result;\n },\n limits,\n );\n\n yield* coordinator.close;\n const result = cleanup;\n const notify = options.onCleanup;\n\n if (result !== undefined) {\n yield* reported(Effect.suspend(() => reportCleanup(result)));\n if (notify !== undefined) yield* reported(Effect.suspend(() => notify(result)));\n }\n }),\n ),\n );\n\n const closeScope = yield* Effect.cached(Scope.close(resourceScope, Exit.void));\n\n // Teardown is registered before the first connection, exactly as an owned scope does.\n yield* Scope.addFinalizer(resourceScope, terminate);\n yield* Scope.addFinalizer(parent, closeScope);\n\n return {\n reference,\n status: observed,\n connection: (timeoutMillis: number) =>\n Effect.suspend(() =>\n closing\n ? Effect.fail(\n SessionError.make({\n operation: \"session-connect\",\n reason: \"expired\",\n outcome: \"undispatched\",\n }),\n )\n : // Credentials are fetched fresh: an expiry can race the caller's own read.\n connectionAddress(client, sessions, reference, timeoutMillis),\n ),\n release: closeScope.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n cleanup === undefined\n ? Effect.die(new Error(\"Borrowed session closed without cleanup evidence\"))\n : Effect.succeed(cleanup),\n ),\n ),\n ),\n cleanupResult: Effect.sync(() => Option.fromNullishOr(cleanup)),\n };\n }),\n );\n});\n","import { type Crypto, Effect, Option, type Redacted } from \"effect\";\nimport type { Lifetime, Source } from \"effect-browser/browser-runtime\";\nimport { BrowserError, Reasons } from \"effect-browser/errors\";\n\nimport type { CleanupResult } from \"../../Cleanup.ts\";\nimport { BrowserbaseClient } from \"../../Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"../../Errors.ts\";\nimport type { LaunchRecipe } from \"../../Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"../../References.ts\";\nimport { BrowserbaseSessions } from \"../../Sessions.ts\";\nimport { issueLiveView, type LiveView } from \"../browser/LiveView.ts\";\nimport { browserRequestFailure } from \"../browser/RequestFailure.ts\";\nimport { acquireRemote } from \"./Acquisition.ts\";\nimport { attachRemote } from \"./Attachment.ts\";\nimport type { ContextWriterPermit } from \"./WriterFacts.ts\";\n\nexport interface RemoteLease extends Lifetime {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly attempt?: AllocationAttempt;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n readonly liveView: (ttl: number) => Effect.Effect<LiveView, BrowserError>;\n}\n\ntype RemoteSource<L extends Lifetime, E> = Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n>;\n\n/** A borrowed connection closes without requiring or requesting remote termination. */\nconst checkedCleanup = (\n close: Effect.Effect<CleanupResult>,\n): Effect.Effect<CleanupResult, BrowserError> =>\n close.pipe(\n Effect.filterOrFail(\n (result) =>\n result.local === \"closed\" &&\n result.issues.length === 0 &&\n (result.ownership === \"borrowed\"\n ? result.remote === \"not-owned\"\n : result.remote === \"confirmed\"),\n () =>\n BrowserError.make({\n operation: \"close\",\n reason: Reasons.Provider.make({}),\n outcome: \"unknown\",\n }),\n ),\n );\n\nconst withConnection = <\n A extends {\n readonly reference: SessionReference;\n readonly connection: (\n timeoutMillis: number,\n ) => Effect.Effect<Redacted.Redacted<string>, SessionError>;\n readonly release: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n },\n>(\n acquired: A,\n) => ({\n ...acquired,\n connection: (timeoutMillis: number) =>\n acquired\n .connection(timeoutMillis)\n .pipe(Effect.mapError((error) => browserRequestFailure(\"connect\", error))),\n closeChecked: checkedCleanup(acquired.release),\n controlRetired: acquired.cleanupResult.pipe(\n Effect.map(\n (result) =>\n Option.isSome(result) &&\n result.value.ownership === \"owned\" &&\n result.value.remote === \"confirmed\",\n ),\n ),\n});\n\nexport interface OwnedLease extends RemoteLease {\n readonly attempt: AllocationAttempt;\n}\n\nexport interface OwnedOptions {\n /** The single provider-faithful launch description; the owner adds no second default body. */\n readonly launch: LaunchRecipe;\n /** Required for a persistent context; the writer permit, not this owner, holds that authority. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\n/** Allocates the session, and therefore owns releasing it. */\nconst providerControls = (\n client: BrowserbaseClient[\"Service\"],\n sessions: BrowserbaseSessions[\"Service\"],\n reference: SessionReference,\n) => ({\n liveView: (ttl: number) => issueLiveView(client, reference, ttl),\n verifyReconnect: sessions.retrieve(reference).pipe(\n Effect.mapError((error) => browserRequestFailure(\"reconnect\", error)),\n Effect.flatMap((status) =>\n status.status === \"RUNNING\"\n ? Effect.void\n : Effect.fail(\n BrowserError.make({\n operation: \"reconnect\",\n reason: Reasons.Expired.make({}),\n outcome: \"undispatched\",\n }),\n ),\n ),\n ),\n});\n\nexport const ownedRemote =\n (\n options: OwnedOptions,\n ): RemoteSource<OwnedLease, AllocationError | BrowserError | ContextError> =>\n (local, lifetimeDeadline) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n\n const acquired = yield* acquireRemote(\n {\n launch: options.launch,\n ...(options.contextWriter === undefined ? {} : { contextWriter: options.contextWriter }),\n allocationDeadline: lifetimeDeadline,\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n },\n local,\n );\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n\n/** Borrows a running session: local connection only, and never a release request. */\nexport const borrowedRemote =\n (options: {\n readonly reference: SessionReference;\n readonly pendingWaitMillis?: number;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n }): RemoteSource<RemoteLease, SessionError> =>\n (local) =>\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const acquired = yield* attachRemote(options, local);\n\n return {\n ...withConnection(acquired),\n ...providerControls(client, sessions, acquired.reference),\n };\n });\n","import {\n Context,\n Crypto,\n Effect,\n Layer,\n type Option,\n type Redacted,\n Schema,\n type Scope,\n} from \"effect\";\nimport type { BrowserSession, OpenOptions } from \"effect-browser/browser\";\nimport type {\n ActionResult,\n AutomationOptions,\n BrowserPolicy,\n ClickRequest,\n Observation,\n} from \"effect-browser/browser-data\";\nimport * as BrowserRuntime from \"effect-browser/browser-runtime\";\nimport {\n BrowserError,\n Reasons,\n type BrowserOperation,\n type InitializationError,\n} from \"effect-browser/errors\";\n\nimport { BrowserbaseBrowserBinding } from \"./BrowserBinding.ts\";\nimport type { CleanupResult } from \"./Cleanup.ts\";\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport type { AllocationError, ContextError, SessionError } from \"./Errors.ts\";\nimport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { isList } from \"./internal/List.ts\";\nimport { borrowedRemote, ownedRemote, type RemoteLease } from \"./internal/session/Browser.ts\";\nimport type { ContextWriterPermit } from \"./internal/session/WriterFacts.ts\";\nimport { issuedUpload } from \"./internal/upload/Issued.ts\";\nimport type { LaunchRecipe } from \"./Launch.ts\";\nimport type { AllocationAttempt, SessionReference } from \"./References.ts\";\nimport { BrowserbaseSessions } from \"./Sessions.ts\";\nimport { DownloadObservation, type SelectFilesRequest } from \"./Transfers.ts\";\n\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { FileSelection, SelectFilesRequest } from \"./Transfers.ts\";\n\n/** Host configuration. Credentials live in the Client; a model never selects these values. */\nexport interface BrowserOptions extends AutomationOptions {\n readonly launch: LaunchRecipe;\n /** Required whenever the launch recipe persists a context. */\n readonly contextWriter?: ContextWriterPermit;\n readonly onCleanup?: (result: CleanupResult) => Effect.Effect<void>;\n readonly onAllocationUncertain?: (attempt: AllocationAttempt) => Effect.Effect<void>;\n}\n\nexport interface Handoff {\n readonly token: Redacted.Redacted<string>;\n readonly view: LiveView;\n}\n\n/** Browserbase identity, remote artifacts and provider cleanup remain hosted capabilities. */\nexport interface BrowserbaseSession<E = never> extends BrowserSession<E> {\n readonly reference: SessionReference;\n readonly closeChecked: Effect.Effect<CleanupResult, BrowserError>;\n readonly clickForDownload: (\n request: ClickRequest,\n ) => Effect.Effect<DownloadObservation, BrowserError>;\n /** Attaches to an existing file input; an uploaded branch needs a receipt for this session. */\n readonly selectFiles: (request: SelectFilesRequest) => Effect.Effect<ActionResult, BrowserError>;\n /** Registers the chooser observation before the single click that opens it. */\n readonly clickForFileSelection: (\n request: SelectFilesRequest,\n ) => Effect.Effect<ActionResult, BrowserError>;\n readonly liveView: (expiresInSeconds?: number) => Effect.Effect<LiveView, BrowserError>;\n readonly beginHandoff: (expiresInSeconds?: number) => Effect.Effect<Handoff, BrowserError>;\n readonly resume: (\n token: Redacted.Redacted<string>,\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError>;\n readonly detach: Effect.Effect<\n { readonly reference: SessionReference; readonly targetId: string },\n BrowserError\n >;\n readonly reconnect: (\n operatorReleasedControl: boolean,\n ) => Effect.Effect<Observation, BrowserError | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n readonly cleanupResult: Effect.Effect<Option.Option<CleanupResult>>;\n}\n\nexport interface AttachRequest<E = never, R = never> extends OpenOptions<E, R> {\n readonly policy: BrowserPolicy;\n /** The exact page to resume; without it the session must have exactly one page. */\n readonly target?: { readonly targetId: string };\n /** Bounded admission of a session the provider has not finished starting. */\n readonly pendingWaitMillis?: number;\n}\n\nexport interface BrowserAcquisition<E = never> {\n readonly reference: SessionReference;\n readonly attempt: AllocationAttempt;\n readonly failure: Effect.Effect<never, E | InitializationError>;\n readonly connect: Effect.Effect<BrowserbaseSession<E>, BrowserError | E | InitializationError>;\n readonly close: Effect.Effect<CleanupResult>;\n}\n\n/** Only receipts issued for this exact provider session may resolve to stored paths. */\nconst selection = (\n request: SelectFilesRequest,\n reference: SessionReference,\n operation: BrowserOperation,\n): Effect.Effect<BrowserRuntime.ResolvedFileSelection, BrowserError> =>\n Effect.suspend(() => {\n if (request.selection._tag === \"Inline\")\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({\n _tag: \"Inline\",\n files: request.selection.files,\n });\n\n const uploads = request.selection.uploads;\n\n if (!isList(uploads) || uploads.length < 1 || uploads.length > 8)\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n }),\n );\n const paths: string[] = [];\n\n for (const receipt of uploads) {\n const issued = issuedUpload(receipt);\n\n if (\n issued === undefined ||\n issued.reference.projectId !== reference.projectId ||\n issued.reference.sessionId !== reference.sessionId\n )\n return Effect.fail(\n BrowserError.make({\n operation,\n reason: Reasons.Authorization.make({}),\n outcome: \"undispatched\",\n }),\n );\n paths.push(issued.remotePath);\n }\n\n return Effect.succeed<BrowserRuntime.ResolvedFileSelection>({ _tag: \"Stored\", paths });\n });\n\nconst makeSession = <E>(\n connection: BrowserRuntime.Connection<SessionReference, E>,\n lifetime: RemoteLease,\n): BrowserbaseSession<E> => {\n const { session, operations } = connection;\n\n // Decorating the same object preserves its private capture and page-control associations.\n return Object.assign(session, {\n reference: lifetime.reference,\n closeChecked: session.closeChecked.pipe(Effect.andThen(lifetime.closeChecked)),\n clickForDownload: (request) =>\n operations.clickForDownload(request).pipe(\n Effect.flatMap((event) =>\n Schema.decodeEffect(DownloadObservation)({\n ...event,\n reference: lifetime.reference,\n }).pipe(\n Effect.mapError(() =>\n BrowserError.make({\n operation: \"download-action\",\n reason: Reasons.Malformed.make({}),\n outcome: \"unknown\",\n }),\n ),\n ),\n ),\n ),\n selectFiles: (request) =>\n selection(request, lifetime.reference, \"select-files\").pipe(\n Effect.flatMap((files) =>\n operations.selectFiles({ selector: request.selector, selection: files }),\n ),\n ),\n clickForFileSelection: (request) =>\n selection(request, lifetime.reference, \"file-chooser\").pipe(\n Effect.flatMap((files) =>\n operations.clickForFileSelection({ selector: request.selector, selection: files }),\n ),\n ),\n liveView: (ttl = 60) => operations.liveView(lifetime.liveView(ttl)),\n beginHandoff: (ttl = 60) => operations.beginHandoff(lifetime.liveView(ttl)),\n resume: operations.resume,\n detach: operations.detach,\n reconnect: operations.reconnect,\n close: lifetime.release,\n cleanupResult: lifetime.cleanupResult,\n } satisfies Omit<BrowserbaseSession<E>, Exclude<keyof BrowserSession<E>, \"closeChecked\">>);\n};\n\nexport class BrowserbaseBrowser extends Context.Service<\n BrowserbaseBrowser,\n {\n readonly acquire: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserAcquisition<E>,\n AllocationError | BrowserError | ContextError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n /** Borrowed control of a session this process did not allocate and will not release. */\n readonly attach: <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n BrowserError | SessionError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n readonly open: <E = never, R = never>(\n policy: BrowserPolicy,\n request?: OpenOptions<E, R>,\n ) => Effect.Effect<\n BrowserbaseSession<E>,\n AllocationError | BrowserError | ContextError | E | InitializationError,\n Scope.Scope | Exclude<R, Scope.Scope>\n >;\n }\n>()(\"effect-browserbase/Browser\") {\n /** Open through the configured account and browser service, in the caller's scope. */\n static open<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.open(policy, request));\n }\n\n /** Allocate the provider lifetime before connecting, preserving its attempt and cleanup. */\n static acquire<E = never, R = never>(policy: BrowserPolicy, request?: OpenOptions<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.acquire(policy, request));\n }\n\n /** Borrow a provider session without acquiring release authority over it. */\n static attach<E = never, R = never>(reference: SessionReference, request: AttachRequest<E, R>) {\n return Effect.flatMap(BrowserbaseBrowser, (browser) => browser.attach(reference, request));\n }\n\n /** Allocation attempts, connection ids and handoff tokens come from the required `Crypto`. */\n static layer(\n options: BrowserOptions,\n ): Layer.Layer<\n BrowserbaseBrowser,\n BrowserError,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n > {\n return Layer.effect(\n BrowserbaseBrowser,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n const sessions = yield* BrowserbaseSessions;\n const crypto = yield* Crypto.Crypto;\n const binding = yield* BrowserbaseBrowserBinding;\n\n if (options.launch.context?.persist === true && options.contextWriter === undefined)\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.ContextLease.make({}),\n outcome: \"undispatched\",\n });\n if (Object.prototype.hasOwnProperty.call(options, \"bootstrap\"))\n return yield* BrowserError.make({\n operation: \"configure\",\n reason: Reasons.Configuration.make({}),\n outcome: \"undispatched\",\n });\n\n const runtime = yield* BrowserRuntime.make({\n implementation: \"browserbase-playwright-cdp\",\n binding,\n automation: projected(options),\n viewport:\n options.launch.viewport._tag === \"Fixed\"\n ? { width: options.launch.viewport.width, height: options.launch.viewport.height }\n : { width: 1280, height: 720 },\n preserveViewport: options.launch.viewport._tag !== \"Fixed\",\n keepAlive: options.launch.keepAlive === true,\n });\n\n const source =\n <L extends BrowserRuntime.Lifetime, E>(\n remote: BrowserRuntime.Source<\n L,\n E,\n BrowserbaseClient | BrowserbaseSessions | Crypto.Crypto\n >,\n ): BrowserRuntime.Source<L, E> =>\n (cleanup, deadline) =>\n remote(cleanup, deadline).pipe(\n Effect.provideService(BrowserbaseClient, client),\n Effect.provideService(BrowserbaseSessions, sessions),\n Effect.provideService(Crypto.Crypto, crypto),\n );\n\n const acquire = Effect.fnUntraced(function* <E = never, R = never>(\n policy: BrowserPolicy,\n request: OpenOptions<E, R> = {},\n ) {\n const acquired = yield* runtime.acquire(\n policy,\n source(\n ownedRemote({\n launch: options.launch,\n ...(options.contextWriter === undefined\n ? {}\n : { contextWriter: options.contextWriter }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n ...(options.onAllocationUncertain === undefined\n ? {}\n : { onAllocationUncertain: options.onAllocationUncertain }),\n }),\n ),\n request,\n );\n\n const connected = yield* Effect.cached(\n acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n ),\n );\n\n return {\n reference: acquired.reference,\n attempt: acquired.lifetime.attempt,\n failure: acquired.failure,\n close: acquired.close,\n connect: acquired.connect.pipe(Effect.andThen(connected)),\n } satisfies BrowserAcquisition<E>;\n });\n\n const attach = Effect.fnUntraced(function* <E = never, R = never>(\n reference: SessionReference,\n request: AttachRequest<E, R>,\n ) {\n const acquired = yield* runtime.acquire(\n request.policy,\n source(\n borrowedRemote({\n reference,\n ...(request.pendingWaitMillis === undefined\n ? {}\n : { pendingWaitMillis: request.pendingWaitMillis }),\n ...(options.onCleanup === undefined ? {} : { onCleanup: options.onCleanup }),\n }),\n ),\n {\n ...(request.bootstrap === undefined ? {} : { bootstrap: request.bootstrap }),\n existingTarget: request.target ?? {},\n },\n );\n\n return yield* acquired.connect.pipe(\n Effect.map((connection) => makeSession(connection, acquired.lifetime)),\n );\n });\n\n return BrowserbaseBrowser.of({\n acquire,\n attach,\n open: (policy, request) =>\n acquire(policy, request).pipe(Effect.flatMap((acquired) => acquired.connect)),\n });\n }),\n );\n }\n}\n\n/** Only the automation fields cross the schema boundary; launch and callbacks are separate. */\nconst projected = (options: BrowserOptions) => ({\n ...(options.maxHostReads === undefined ? {} : { maxHostReads: options.maxHostReads }),\n ...(options.actionTimeoutMillis === undefined\n ? {}\n : { actionTimeoutMillis: options.actionTimeoutMillis }),\n ...(options.maxPages === undefined ? {} : { maxPages: options.maxPages }),\n ...(options.initialPage === undefined ? {} : { initialPage: options.initialPage }),\n ...(options.popupPolicy === undefined ? {} : { popupPolicy: options.popupPolicy }),\n ...(options.dialogPolicy === undefined ? {} : { dialogPolicy: options.dialogPolicy }),\n ...(options.pageControl === undefined ? {} : { pageControl: options.pageControl }),\n});\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAM,WAAW,WACf,aAAa,KAAK;CAAE,WAAW;CAAkB;CAAQ,SAAS;AAAe,CAAC;;;;;;AAOpF,MAAa,eAAe,OAAO,WAAW,WAC5C,SACA,QAAsB,mBACtB,QACA;CACA,MAAM,SAAS,OAAO;CACtB,MAAM,WAAW,OAAO;CACxB,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,oBAAoB,QAAQ,qBAAqB;CAEvD,IACE,CAAC,OAAO,cAAc,iBAAiB,KACvC,oBAAoB,KACpB,oBAAoB,KAEpB,OAAO,OAAO,QAAQ,eAAe;CAIvC,MAAM,WAAW,OAAO,SAAS,SAAS,QAAQ,SAAS;CAE3D,IAAI,wBAAwB,SAAS,MAAM,GAAG,OAAO,OAAO,QAAQ,SAAS;CAC7E,IAAI,SAAS,WAAW,WAAW;EACjC,IAAI,sBAAsB,GAAG,OAAO,OAAO,QAAQ,QAAQ;EAC3D,OAAO,SAAS,iBAAiB,SAAS,WAAW,EAAE,eAAe,kBAAkB,CAAC;CAC3F;CACA,MAAM,YAAY,SAAS;CAE3B,OAAO,OAAO,OAAO,gBACnB,OAAO,IAAI,aAAa;EACtB,MAAM,gBAAgB,OAAO,MAAM,KAAK;EACxC,IAAI,UAAU;EACd,IAAI;EAEJ,MAAM,YAAY,OAAO,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AAQ,SAAS;CACvE,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAChF,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;CAChF,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;CACnF,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;AAClF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Client-4RMKIpL2.mjs","names":[],"sources":["../src/internal/http/Multipart.ts","../src/internal/http/Transport.ts","../src/Client.ts"],"sourcesContent":["import { Effect, Random, Schema } from \"effect\";\n\nimport type { MultipartFile } from \"../../Client.ts\";\nimport { SafeFilename } from \"../../Transfers.ts\";\n\n/** One file part is the only multipart shape this transport produces. */\nexport type MultipartResult =\n | {\n readonly _tag: \"Encoded\";\n readonly contentType: string;\n readonly body: Uint8Array;\n }\n | { readonly _tag: \"Rejected\"; readonly reason: \"configuration\" | \"limit\" };\n\nconst FIELD = /^[a-z][a-z0-9_]{0,31}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_+.-]{0,63}\\/[a-z0-9][a-z0-9!#$&^_+.-]{0,63}$/;\nconst PRINTABLE_ASCII = /^[\\x20-\\x7e]+$/;\n\nconst isSafeFilename = Schema.is(SafeFilename);\n\n/** Quoting is only safe for a portable, printable, quote-free basename. */\nconst quotable = (value: string): boolean =>\n isSafeFilename(value) && PRINTABLE_ASCII.test(value) && !value.includes('\"');\n\n/**\n * Sixteen bytes from the fiber's `Random`. A boundary needs no secrecy: the encoder checks that\n * the content does not contain it, and draws another if it does.\n */\nconst randomBoundary: Effect.Effect<string> = Effect.map(\n Effect.all(Array.from({ length: 16 }, () => Random.nextIntBetween(0, 255))),\n (bytes) =>\n `effect-agent-browserbase-${bytes.map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`,\n);\n\nconst contains = (haystack: Uint8Array, needle: Uint8Array): boolean => {\n const first = needle[0];\n\n if (first === undefined || needle.length > haystack.length) return false;\n\n outer: for (let i = 0; i <= haystack.length - needle.length; i++) {\n if (haystack[i] !== first) continue;\n for (let j = 1; j < needle.length; j++) {\n const expected = needle[j];\n\n if (expected === undefined || haystack[i + j] !== expected) continue outer;\n }\n\n return true;\n }\n\n return false;\n};\n\n/**\n * A deliberately small RFC 7578 encoder: one file part, an ASCII-quotable name and a\n * delimiter proven absent from the content. It performs no filesystem or stream work.\n */\nexport const encodeFilePart = Effect.fnUntraced(function* (\n part: MultipartFile,\n maxBytes: number,\n boundaries: Effect.Effect<string> = randomBoundary,\n): Effect.fn.Return<MultipartResult> {\n if (\n !FIELD.test(part.field) ||\n !quotable(part.filename) ||\n !MEDIA_TYPE.test(part.mediaType) ||\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n maxBytes > 2 ** 31 - 1\n ) {\n return { _tag: \"Rejected\", reason: \"configuration\" };\n }\n if (part.bytes.byteLength > maxBytes) return { _tag: \"Rejected\", reason: \"limit\" };\n const encoder = new TextEncoder();\n\n for (let attempt = 0; attempt < 4; attempt++) {\n const boundary = yield* boundaries;\n\n if (!/^[A-Za-z0-9-]{1,70}$/.test(boundary)) continue;\n const delimiter = encoder.encode(boundary);\n\n if (contains(part.bytes, delimiter)) continue;\n\n const head = encoder.encode(\n `--${boundary}\\r\\nContent-Disposition: form-data; name=\"${part.field}\"; filename=\"${part.filename}\"\\r\\nContent-Type: ${part.mediaType}\\r\\n\\r\\n`,\n );\n\n const tail = encoder.encode(`\\r\\n--${boundary}--\\r\\n`);\n const body = new Uint8Array(head.byteLength + part.bytes.byteLength + tail.byteLength);\n\n body.set(head, 0);\n body.set(part.bytes, head.byteLength);\n body.set(tail, head.byteLength + part.bytes.byteLength);\n\n return {\n _tag: \"Encoded\",\n contentType: `multipart/form-data; boundary=${boundary}`,\n body,\n };\n }\n\n return { _tag: \"Rejected\", reason: \"configuration\" };\n});\n","import { Clock, Duration, Effect, Redacted, Schema, Stream } from \"effect\";\nimport {\n FetchHttpClient,\n HttpClient,\n HttpClientRequest,\n type HttpClientResponse,\n} from \"effect/unstable/http\";\n\nimport type { ClientMethod, ClientOptions, MultipartFile, UploadLimits } from \"../../Client.ts\";\nimport { ClientError } from \"../../Errors.ts\";\nimport { Identifier } from \"../../References.ts\";\nimport { encodeFilePart } from \"./Multipart.ts\";\n\nconst API_ORIGIN = \"https://api.browserbase.com\";\nconst MAX_JSON_BYTES = 1024 * 1024;\nconst MAX_JSON_DEPTH = 64;\n\nconst Options = Schema.Struct({\n projectId: Identifier,\n apiKey: Schema.Redacted(\n Schema.NonEmptyString.check(Schema.isMaxLength(8192), Schema.isPattern(/^[\\x21-\\x7e]+$/)),\n ),\n artifactOrigins: Schema.optionalKey(\n Schema.Array(Schema.String.check(Schema.isMaxLength(8192))).check(\n Schema.isMaxLength(32),\n Schema.isUnique(),\n ),\n ),\n requestTimeoutMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 60_000 })),\n ),\n});\n\nconst nowMillis = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1_000_000));\n\nconst deadlineAfter = (millis: number) => nowMillis.pipe(Effect.map((now) => now + millis));\n\nconst within = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n deadline: number,\n operation: ClientError[\"operation\"],\n outcome?: \"undispatched\" | \"unknown\",\n): Effect.Effect<A, E | ClientError, R> =>\n Effect.suspend(() =>\n nowMillis.pipe(\n Effect.flatMap((now) => {\n const remaining = deadline - now;\n\n const timeout = () =>\n Effect.fail(\n ClientError.make({\n operation,\n reason: \"timeout\",\n ...(outcome === undefined ? {} : { outcome }),\n }),\n );\n\n return remaining <= 0\n ? timeout()\n : effect.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(remaining),\n orElse: timeout,\n }),\n );\n }),\n ),\n );\n\nconst withinJsonDepth = (text: string): boolean => {\n let depth = 0;\n let quoted = false;\n let escaped = false;\n\n for (const character of text) {\n if (quoted) {\n if (escaped) escaped = false;\n else if (character === \"\\\\\") escaped = true;\n else if (character === '\"') quoted = false;\n } else if (character === '\"') quoted = true;\n else if (character === \"{\" || character === \"[\") {\n if (++depth > MAX_JSON_DEPTH) return false;\n } else if (character === \"}\" || character === \"]\") depth--;\n }\n\n return true;\n};\n\nconst mediaType = (value: string | undefined): string =>\n value?.split(\";\", 1)[0]?.trim().toLowerCase() ?? \"\";\n\nconst retryAfter = (value: string | undefined, now: number): number | undefined => {\n if (value === undefined || value.length > 128) return undefined;\n const seconds = Number(value);\n\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(60_000, seconds * 1000);\n const date = Date.parse(value);\n\n return Number.isFinite(date) ? Math.min(60_000, Math.max(0, date - now)) : undefined;\n};\n\nconst mutationOutcome = (\n method: ClientMethod,\n status?: number,\n): \"rejected\" | \"unknown\" | undefined => {\n if (method === \"GET\") return undefined;\n if (status !== undefined && [400, 401, 403, 404, 409, 410, 422, 429].includes(status)) {\n return \"rejected\";\n }\n\n return \"unknown\";\n};\n\nconst statusError = (\n method: ClientMethod,\n status: number,\n operation: ClientError[\"operation\"],\n after?: number,\n) =>\n ClientError.make({\n operation,\n reason:\n status === 401 || status === 403\n ? \"authorization\"\n : status === 429\n ? \"rate-limited\"\n : status === 409\n ? \"active\"\n : status === 410\n ? \"expired\"\n : status === 422\n ? \"disabled\"\n : status === 404\n ? \"not-found\"\n : \"provider\",\n status,\n ...(mutationOutcome(method, status) === undefined\n ? {}\n : { outcome: mutationOutcome(method, status) }),\n ...(after === undefined ? {} : { retryAfterMillis: after }),\n });\n\nconst collect = (\n stream: Stream.Stream<Uint8Array, ClientError>,\n maximum: number,\n operation: ClientError[\"operation\"],\n) =>\n Effect.gen(function* () {\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n yield* Stream.runForEach(stream, (chunk) =>\n Effect.suspend(() => {\n if (chunk.byteLength > maximum - total) {\n return Effect.fail(ClientError.make({ operation, reason: \"limit\" }));\n }\n total += chunk.byteLength;\n chunks.push(chunk);\n\n return Effect.void;\n }),\n );\n\n const body = new Uint8Array(total);\n let offset = 0;\n\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return body;\n });\n\nconst validApiPath = (path: string): boolean =>\n path.startsWith(\"/v1/\") && !path.includes(\"\\\\\") && !path.includes(\"#\") && path.length <= 16_384;\n\nexport const makeTransport = Effect.fnUntraced(function* (options: ClientOptions) {\n const configured = yield* Schema.decodeEffect(Options)(options, {\n onExcessProperty: \"error\",\n }).pipe(\n Effect.mapError(() =>\n ClientError.make({\n operation: \"configure\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n }),\n ),\n );\n\n const apiKey = Redacted.value(configured.apiKey);\n const requestTimeoutMillis = configured.requestTimeoutMillis ?? 10_000;\n const artifactOrigins = new Set<string>();\n\n for (const origin of configured.artifactOrigins ?? []) {\n const url = yield* Effect.try({\n try: () => new URL(origin),\n catch: () =>\n ClientError.make({\n operation: \"configure\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n }),\n });\n\n if (url.protocol !== \"https:\" || url.origin !== origin || url.username || url.password) {\n return yield* ClientError.make({\n operation: \"configure\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n }\n artifactOrigins.add(origin);\n }\n\n const fetch = yield* FetchHttpClient.Fetch;\n const client = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer));\n const scoped = HttpClient.withScope(client);\n\n const execute = (\n request: HttpClientRequest.HttpClientRequest,\n operation: ClientError[\"operation\"],\n outcome?: \"undispatched\" | \"unknown\",\n ) =>\n scoped.execute(request).pipe(\n Effect.provideService(FetchHttpClient.Fetch, fetch),\n Effect.provideService(FetchHttpClient.RequestInit, {\n redirect: \"manual\",\n credentials: \"omit\",\n cache: \"no-store\",\n referrerPolicy: \"no-referrer\",\n }),\n Effect.provideService(HttpClient.TracerDisabledWhen, () => true),\n Effect.provideService(HttpClient.TracerPropagationEnabled, false),\n Effect.withTracerEnabled(false),\n Effect.mapError(() =>\n ClientError.make({\n operation,\n reason: \"transport\",\n ...(outcome === undefined ? {} : { outcome }),\n }),\n ),\n );\n\n /** A rejected path is a typed, undispatched configuration failure, never a defect. */\n const apiRequest = (\n method: ClientMethod,\n path: string,\n accept: string,\n operation: ClientError[\"operation\"],\n ) =>\n validApiPath(path)\n ? Effect.succeed(\n HttpClientRequest.make(method)(`${API_ORIGIN}${path}`).pipe(\n HttpClientRequest.setHeader(\"x-bb-api-key\", apiKey),\n HttpClientRequest.setHeader(\"accept\", accept),\n ),\n )\n : Effect.fail(\n ClientError.make({ operation, reason: \"configuration\", outcome: \"undispatched\" }),\n );\n\n const inspectJson = Effect.fnUntraced(function* (\n method: ClientMethod,\n response: HttpClientResponse.HttpClientResponse,\n operation: ClientError[\"operation\"],\n ) {\n if (response.status !== 200 && response.status !== 201 && response.status !== 202) {\n return yield* statusError(\n method,\n response.status,\n operation,\n retryAfter(response.headers[\"retry-after\"], yield* Clock.currentTimeMillis),\n );\n }\n if (mediaType(response.headers[\"content-type\"]) !== \"application/json\") {\n return yield* ClientError.make({\n operation,\n reason: \"content-type\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n });\n }\n const length = response.headers[\"content-length\"];\n\n if (length !== undefined && (!/^\\d+$/.test(length) || Number(length) > MAX_JSON_BYTES)) {\n return yield* ClientError.make({\n operation,\n reason: \"limit\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n });\n }\n let received = 0;\n\n return response.stream.pipe(\n Stream.mapError(() =>\n ClientError.make({\n operation,\n reason: \"transport\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n }),\n ),\n Stream.mapEffect((chunk) =>\n Effect.suspend(() => {\n if (chunk.byteLength > MAX_JSON_BYTES - received) {\n return Effect.fail(\n ClientError.make({\n operation,\n reason: \"limit\",\n ...(mutationOutcome(method) === undefined\n ? {}\n : { outcome: mutationOutcome(method) }),\n }),\n );\n }\n received += chunk.byteLength;\n\n return Effect.succeed(new Uint8Array(chunk));\n }),\n ),\n );\n });\n\n const readJson = Effect.fnUntraced(function* (\n method: ClientMethod,\n response: HttpClientResponse.HttpClientResponse,\n operation: ClientError[\"operation\"],\n ) {\n const stream = yield* inspectJson(method, response, operation);\n const bytes = yield* collect(stream, MAX_JSON_BYTES, operation);\n\n const text = yield* Effect.try({\n try: () => new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes),\n catch: () =>\n ClientError.make({\n operation,\n reason: \"malformed\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n }),\n });\n\n if (!withinJsonDepth(text)) {\n return yield* ClientError.make({\n operation,\n reason: \"limit\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n });\n }\n\n return yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(text).pipe(\n Effect.mapError(() =>\n ClientError.make({\n operation,\n reason: \"malformed\",\n ...(mutationOutcome(method) === undefined ? {} : { outcome: mutationOutcome(method) }),\n }),\n ),\n );\n });\n\n const jsonOnce = Effect.fnUntraced(function* (\n method: ClientMethod,\n path: string,\n body?: Schema.Json,\n ) {\n const operation = method === \"GET\" ? \"provider-read\" : \"provider-mutation\";\n let request = yield* apiRequest(method, path, \"application/json\", operation);\n\n if (body !== undefined) {\n request = yield* HttpClientRequest.bodyJson(request, body).pipe(\n Effect.mapError(() =>\n ClientError.make({\n operation,\n reason: \"configuration\",\n outcome: \"undispatched\",\n }),\n ),\n );\n }\n const response = yield* execute(request, operation, method === \"GET\" ? undefined : \"unknown\");\n\n return yield* readJson(method, response, operation);\n });\n\n /**\n * One bounded in-memory file part. The encoder proves its delimiter absent from the\n * content, and an accepted multipart mutation is never retried: a lost reply is unknown.\n */\n const upload = Effect.fnUntraced(function* (\n path: string,\n part: MultipartFile,\n limits: UploadLimits,\n outerDeadline?: number,\n ) {\n const operation = \"provider-upload\";\n const timeoutMillis = limits.timeoutMillis ?? 60_000;\n\n if (!Number.isSafeInteger(timeoutMillis) || timeoutMillis < 1 || timeoutMillis > 600_000) {\n return yield* ClientError.make({\n operation,\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n }\n\n const encoded = yield* encodeFilePart(part, limits.maxBytes);\n\n if (encoded._tag === \"Rejected\") {\n return yield* ClientError.make({\n operation,\n reason: encoded.reason,\n outcome: \"undispatched\",\n });\n }\n\n const request = HttpClientRequest.bodyUint8Array(\n yield* apiRequest(\"POST\", path, \"application/json\", operation),\n encoded.body,\n encoded.contentType,\n );\n\n const deadline = Math.min(yield* deadlineAfter(timeoutMillis), outerDeadline ?? Infinity);\n\n return yield* within(\n Effect.scoped(\n execute(request, operation, \"unknown\").pipe(\n Effect.flatMap((response) => readJson(\"POST\", response, operation)),\n ),\n ),\n deadline,\n operation,\n \"unknown\",\n );\n });\n\n const json = Effect.fnUntraced(function* (\n method: ClientMethod,\n path: string,\n body?: Schema.Json,\n outerDeadline?: number,\n ) {\n const deadline = Math.min(\n yield* deadlineAfter(requestTimeoutMillis),\n outerDeadline ?? Infinity,\n );\n\n for (let attempt = 0; ; attempt++) {\n const result = yield* within(\n Effect.scoped(jsonOnce(method, path, body)),\n deadline,\n // A request that times out is labelled like the same request failing any other way.\n method === \"GET\" ? \"provider-read\" : \"provider-mutation\",\n method === \"GET\" ? undefined : \"unknown\",\n ).pipe(Effect.result);\n\n if (result._tag === \"Success\") return result.success;\n const error = result.failure;\n\n const retryable =\n error.reason === \"transport\" ||\n error.reason === \"rate-limited\" ||\n (error.reason === \"provider\" && (error.status ?? 0) >= 500);\n\n if (method !== \"GET\" || !retryable || attempt >= 2) return yield* error;\n const delay = error.retryAfterMillis ?? (attempt + 1) * 150;\n\n if ((yield* nowMillis) + delay >= deadline) return yield* error;\n yield* Effect.sleep(delay);\n }\n });\n\n const noContent = Effect.fnUntraced(function* (\n method: Exclude<ClientMethod, \"GET\">,\n path: string,\n body?: Schema.Json,\n outerDeadline?: number,\n ) {\n const operation = \"provider-mutation\";\n let request = yield* apiRequest(method, path, \"*/*\", operation);\n\n if (body !== undefined) {\n request = yield* HttpClientRequest.bodyJson(request, body).pipe(\n Effect.mapError(() =>\n ClientError.make({\n operation,\n reason: \"configuration\",\n outcome: \"undispatched\",\n }),\n ),\n );\n }\n\n const deadline = Math.min(\n yield* deadlineAfter(requestTimeoutMillis),\n outerDeadline ?? Infinity,\n );\n\n const response = yield* within(\n Effect.scoped(execute(request, operation, \"unknown\")),\n deadline,\n operation,\n \"unknown\",\n );\n\n if (![200, 202, 204].includes(response.status)) {\n return yield* statusError(\n method,\n response.status,\n operation,\n retryAfter(response.headers[\"retry-after\"], yield* Clock.currentTimeMillis),\n );\n }\n });\n\n const inspectBytes = Effect.fnUntraced(function* (\n response: HttpClientResponse.HttpClientResponse,\n operation: ClientError[\"operation\"],\n types: ReadonlyArray<string>,\n maximum: number,\n ) {\n if (response.status !== 200 && response.status !== 206) {\n return yield* statusError(\n \"GET\",\n response.status,\n operation,\n retryAfter(response.headers[\"retry-after\"], yield* Clock.currentTimeMillis),\n );\n }\n if (!types.includes(mediaType(response.headers[\"content-type\"]))) {\n return yield* ClientError.make({ operation, reason: \"content-type\" });\n }\n const length = response.headers[\"content-length\"];\n\n if (length !== undefined && (!/^\\d+$/.test(length) || Number(length) > maximum)) {\n return yield* ClientError.make({ operation, reason: \"limit\" });\n }\n let received = 0;\n\n return response.stream.pipe(\n Stream.mapError(() => ClientError.make({ operation, reason: \"transport\" })),\n Stream.mapEffect((chunk) =>\n Effect.suspend(() => {\n if (chunk.byteLength > maximum - received) {\n return Effect.fail(ClientError.make({ operation, reason: \"limit\" }));\n }\n received += chunk.byteLength;\n\n return Effect.succeed(new Uint8Array(chunk));\n }),\n ),\n );\n });\n\n const bytes = (\n path: string,\n maximum: number,\n types: ReadonlyArray<string>,\n timeoutMillis = requestTimeoutMillis,\n outerDeadline?: number,\n ) =>\n Stream.unwrap(\n Effect.gen(function* () {\n // A bounded authenticated read. Resource services relabel it with their own operation.\n const operation = \"provider-read\";\n\n if (\n !Number.isSafeInteger(maximum) ||\n maximum < 1 ||\n maximum > 2 ** 31 - 1 ||\n !Number.isSafeInteger(timeoutMillis) ||\n timeoutMillis < 1 ||\n timeoutMillis > 600_000\n ) {\n return yield* ClientError.make({ operation, reason: \"configuration\" });\n }\n const deadline = Math.min(yield* deadlineAfter(timeoutMillis), outerDeadline ?? Infinity);\n\n const request = yield* apiRequest(\n \"GET\",\n path,\n types[0] ?? \"application/octet-stream\",\n operation,\n );\n\n const response = yield* within(execute(request, operation), deadline, operation);\n\n const stream = yield* inspectBytes(response, operation, types, maximum);\n\n return Stream.transformPull(stream, (pull) =>\n Effect.succeed(within(pull, deadline, operation)),\n );\n }),\n ).pipe(Stream.scoped);\n\n const text = (path: string, maximum: number, types: ReadonlyArray<string>) =>\n collect(bytes(path, maximum, types), maximum, \"provider-read\").pipe(\n Effect.flatMap((body) =>\n Effect.try({\n try: () => new TextDecoder(\"utf-8\", { fatal: true }).decode(body),\n catch: () => ClientError.make({ operation: \"provider-read\", reason: \"malformed\" }),\n }),\n ),\n Effect.timeoutOrElse({\n duration: Duration.millis(requestTimeoutMillis),\n orElse: () =>\n Effect.fail(ClientError.make({ operation: \"provider-read\", reason: \"timeout\" })),\n }),\n );\n\n const validateMediaUrl = (value: string): boolean => {\n try {\n const url = new URL(value);\n\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n !url.hash &&\n artifactOrigins.has(url.origin) &&\n value.length <= 16_384\n );\n } catch {\n return false;\n }\n };\n\n const media = (\n url: Redacted.Redacted<string>,\n maximum: number,\n types: ReadonlyArray<string>,\n timeoutMillis = 60_000,\n outerDeadline?: number,\n ) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const value = Redacted.value(url);\n\n if (\n !validateMediaUrl(value) ||\n !Number.isSafeInteger(maximum) ||\n maximum < 1 ||\n maximum > 2 ** 31 - 1 ||\n !Number.isSafeInteger(timeoutMillis) ||\n timeoutMillis < 1 ||\n timeoutMillis > 600_000\n ) {\n return yield* ClientError.make({ operation: \"media-download\", reason: \"unsafe-url\" });\n }\n const deadline = Math.min(yield* deadlineAfter(timeoutMillis), outerDeadline ?? Infinity);\n\n const response = yield* within(\n execute(HttpClientRequest.get(value), \"media-download\"),\n deadline,\n \"media-download\",\n );\n\n const stream = yield* inspectBytes(response, \"media-download\", types, maximum);\n\n return Stream.transformPull(stream, (pull) =>\n Effect.succeed(within(pull, deadline, \"media-download\")),\n );\n }),\n ).pipe(Stream.scoped);\n\n return {\n projectId: configured.projectId,\n json,\n noContent,\n upload,\n text,\n bytes,\n media,\n validateMediaUrl,\n };\n});\n","import { Config, Context, Effect, Layer, type Redacted, type Schema, type Stream } from \"effect\";\n\nimport type { ClientError } from \"./Errors.ts\";\nimport { makeTransport } from \"./internal/http/Transport.ts\";\n\n/** Account authority only. Launch recipes and browser-operation policy do not belong here. */\nexport interface ClientOptions {\n readonly projectId: string;\n readonly apiKey: Redacted.Redacted<string>;\n /** Exact HTTPS origins approved for credential-free media/artifact transfers. */\n readonly artifactOrigins?: ReadonlyArray<string>;\n readonly requestTimeoutMillis?: number;\n}\n\nexport type ClientMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** One bounded in-memory file part. A filesystem path is never a transport input. */\nexport interface MultipartFile {\n readonly field: string;\n readonly filename: string;\n readonly mediaType: string;\n readonly bytes: Uint8Array;\n}\n\n/** Upload bounds are caller-owned; an omitted timeout keeps the 60-second default. */\nexport interface UploadLimits {\n readonly maxBytes: number;\n readonly timeoutMillis?: number;\n}\n\n/**\n * One immutable Browserbase account and approved transport, shared by every resource Layer.\n * Constructing the Layer performs no request and never loads the native browser peer.\n */\nexport class BrowserbaseClient extends Context.Service<\n BrowserbaseClient,\n {\n readonly projectId: string;\n readonly json: (\n method: ClientMethod,\n path: string,\n body?: Schema.Json,\n outerDeadline?: number,\n ) => Effect.Effect<Schema.Json, ClientError>;\n readonly noContent: (\n method: Exclude<ClientMethod, \"GET\">,\n path: string,\n body?: Schema.Json,\n outerDeadline?: number,\n ) => Effect.Effect<void, ClientError>;\n /** One bounded multipart mutation. A lost reply stays unknown and is never retried. */\n readonly upload: (\n path: string,\n part: MultipartFile,\n limits: UploadLimits,\n outerDeadline?: number,\n ) => Effect.Effect<Schema.Json, ClientError>;\n readonly text: (\n path: string,\n maximum: number,\n types: ReadonlyArray<string>,\n ) => Effect.Effect<string, ClientError>;\n readonly bytes: (\n path: string,\n maximum: number,\n types: ReadonlyArray<string>,\n timeoutMillis?: number,\n outerDeadline?: number,\n ) => Stream.Stream<Uint8Array, ClientError>;\n readonly media: (\n url: Redacted.Redacted<string>,\n maximum: number,\n types: ReadonlyArray<string>,\n timeoutMillis?: number,\n outerDeadline?: number,\n ) => Stream.Stream<Uint8Array, ClientError>;\n readonly validateMediaUrl: (value: string) => boolean;\n }\n>()(\"effect-browserbase/Client\") {\n static layer(options: ClientOptions): Layer.Layer<BrowserbaseClient, ClientError> {\n return Layer.effect(\n BrowserbaseClient,\n makeTransport(options).pipe(\n Effect.map((client) => BrowserbaseClient.of(Object.freeze(client))),\n ),\n );\n }\n\n /**\n * Account authority from the application's `ConfigProvider` (the environment by default):\n * `BROWSERBASE_PROJECT_ID` and a redacted `BROWSERBASE_API_KEY`. Transport options stay\n * explicit. Configuration is read when the Layer is built, never at import.\n */\n static layerConfig(\n options: Omit<ClientOptions, \"projectId\" | \"apiKey\"> = {},\n ): Layer.Layer<BrowserbaseClient, ClientError | Config.ConfigError> {\n return Layer.unwrap(\n Effect.gen(function* () {\n const projectId = yield* Config.String(\"BROWSERBASE_PROJECT_ID\");\n const apiKey = yield* Config.Redacted(\"BROWSERBASE_API_KEY\");\n\n return BrowserbaseClient.layer({ ...options, projectId, apiKey });\n }),\n );\n }\n}\n"],"mappings":";;;;;;AAcA,MAAM,QAAQ;AACd,MAAM,aAA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KAAK;GAAE,WAAW;GAAkB,QAAQ;EAAa,CAAC;EAEtF,MAAM,WAAW,KAAK,IAAI,OAAO,cAAc,aAAa,GAAG,iBAAiB,QAAQ;EAExF,MAAM,WAAW,OAAO,OACtB,QAAQ,kBAAkB,IAAI,KAAK,GAAG,gBAAgB,GACtD,UACA,gBACF;EAEA,MAAM,SAAS,OAAO,aAAa,UAAU,kBAAkB,OAAO,OAAO;EAE7E,OAAO,OAAO,cAAc,SAAS,SACnC,OAAO,QAAQ,OAAO,MAAM,UAAU,gBAAgB,CAAC,CACzD;CACF,CAAC,CACH,CAAC,CAAC,KAAK,OAAO,MAAM;CAEtB,OAAO;EACL,WAAW,WAAW;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF,CAAC;;;;;;;AC/nBD,IAAa,oBAAb,MAAa,0BAA0B,QAAQ,QA4C7C,CAAC,CAAC,2BAA2B,CAAC,CAAC;CAC/B,OAAO,MAAM,SAAqE;EAChF,OAAO,MAAM,OACX,mBACA,cAAc,OAAO,CAAC,CAAC,KACrB,OAAO,KAAK,WAAW,kBAAkB,GAAG,OAAO,OAAO,MAAM,CAAC,CAAC,CACpE,CACF;CACF;;;;;;CAOA,OAAO,YACL,UAAuD,CAAC,GACU;EAClE,OAAO,MAAM,OACX,OAAO,IAAI,aAAa;GACtB,MAAM,YAAY,OAAO,OAAO,OAAO,wBAAwB;GAC/D,MAAM,SAAS,OAAO,OAAO,SAAS,qBAAqB;GAE3D,OAAO,kBAAkB,MAAM;IAAE,GAAG;IAAS;IAAW;GAAO,CAAC;EAClE,CAAC,CACH;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Extensions-Dg3jHOf0.mjs","names":[],"sources":["../src/internal/extension/Archive.ts","../src/Extensions.ts"],"sourcesContent":["/**\n * A bounded, allocation-free inspection of an extension ZIP: enough to prove a root\n * `manifest.json` and reject traversal before an upload, never an extractor. No entry is\n * decompressed and no path is written; the provider remains the loader of record.\n */\nexport interface ArchiveFacts {\n readonly entries: number;\n /** Uncompressed size the central directory itself declares, not a measured expansion. */\n readonly declaredBytes: number;\n}\n\nexport type ArchiveRejection =\n | \"signature\"\n | \"malformed\"\n | \"unsupported\"\n | \"name\"\n | \"manifest\"\n | \"limit\";\n\nexport type ArchiveResult =\n | { readonly _tag: \"Accepted\"; readonly facts: ArchiveFacts }\n | { readonly _tag: \"Rejected\"; readonly reason: ArchiveRejection };\n\nconst MAX_ENTRIES = 4096;\nconst MAX_NAME_BYTES = 512;\nconst MAX_DECLARED_BYTES = 512 * 1024 * 1024;\nconst EOCD_SIZE = 22;\nconst LOCAL_HEADER_SIZE = 30;\nconst STORED = 0;\nconst DEFLATED = 8;\n\nconst LOCAL_HEADER = 0x04034b50;\nconst CENTRAL_HEADER = 0x02014b50;\nconst END_OF_CENTRAL_DIRECTORY = 0x06054b50;\n\nconst rejected = (reason: ArchiveRejection): ArchiveResult => ({ _tag: \"Rejected\", reason });\n\nconst control = (name: string): boolean =>\n [...name].some((character) => character < \" \" || character === \"\\x7f\");\n\n/** Any `..` or rooted member would name a file outside the extension directory. */\nconst unsafeName = (name: string): boolean =>\n name.length === 0 ||\n name.startsWith(\"/\") ||\n name.includes(\"\\\\\") ||\n name.includes(\"//\") ||\n /^[A-Za-z]:/.test(name) ||\n control(name) ||\n name.split(\"/\").some((segment) => segment === \".\" || segment === \"..\");\n\nexport const inspectExtensionArchive = (archive: Uint8Array): ArchiveResult => {\n if (archive.byteLength < EOCD_SIZE) return rejected(\"malformed\");\n const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength);\n const u16 = (offset: number) => view.getUint16(offset, true);\n const u32 = (offset: number) => view.getUint32(offset, true);\n\n if (u32(0) !== LOCAL_HEADER) return rejected(\"signature\");\n\n // The comment is bounded by its own 16-bit length, so the record cannot hide further back.\n const earliest = Math.max(0, archive.byteLength - EOCD_SIZE - 0xffff);\n let end = -1;\n\n for (let offset = archive.byteLength - EOCD_SIZE; offset >= earliest; offset--) {\n if (u32(offset) === END_OF_CENTRAL_DIRECTORY) {\n end = offset;\n break;\n }\n }\n if (end < 0) return rejected(\"malformed\");\n\n const entries = u16(end + 10);\n const directorySize = u32(end + 12);\n const directoryOffset = u32(end + 16);\n const commentLength = u16(end + 20);\n\n if (u16(end + 4) !== 0 || u16(end + 6) !== 0 || u16(end + 8) !== entries)\n return rejected(\"unsupported\");\n if (entries === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff)\n return rejected(\"unsupported\");\n if (end + EOCD_SIZE + commentLength !== archive.byteLength) return rejected(\"malformed\");\n if (directoryOffset + directorySize > end) return rejected(\"malformed\");\n if (entries > MAX_ENTRIES) return rejected(\"limit\");\n\n const names = new TextDecoder(\"utf-8\", { fatal: true });\n const limit = directoryOffset + directorySize;\n let offset = directoryOffset;\n let declaredBytes = 0;\n let manifest = false;\n\n for (let index = 0; index < entries; index++) {\n if (offset + 46 > limit || u32(offset) !== CENTRAL_HEADER) return rejected(\"malformed\");\n const flags = u16(offset + 8);\n const method = u16(offset + 10);\n const compressed = u32(offset + 20);\n const declared = u32(offset + 24);\n const nameLength = u16(offset + 28);\n const extraLength = u16(offset + 30);\n const entryCommentLength = u16(offset + 32);\n const localOffset = u32(offset + 42);\n\n if (declared === 0xffffffff || compressed === 0xffffffff || localOffset === 0xffffffff)\n return rejected(\"unsupported\");\n // An encrypted or unusually compressed member is not something a browser will load.\n if ((flags & 1) !== 0 || (method !== STORED && method !== DEFLATED))\n return rejected(\"unsupported\");\n if (nameLength === 0 || nameLength > MAX_NAME_BYTES) return rejected(\"name\");\n if (offset + 46 + nameLength + extraLength + entryCommentLength > limit)\n return rejected(\"malformed\");\n if (localOffset >= directoryOffset) return rejected(\"malformed\");\n\n let name: string;\n\n try {\n name = names.decode(archive.subarray(offset + 46, offset + 46 + nameLength));\n } catch {\n return rejected(\"name\");\n }\n if (unsafeName(name)) return rejected(\"name\");\n\n // The directory must agree with the local header it points at: a member that describes\n // itself differently in two places has no single meaning worth uploading.\n if (localOffset + LOCAL_HEADER_SIZE > directoryOffset || u32(localOffset) !== LOCAL_HEADER)\n return rejected(\"malformed\");\n const localNameLength = u16(localOffset + 26);\n const localStart = localOffset + LOCAL_HEADER_SIZE;\n\n if (\n (u16(localOffset + 6) & 1) !== 0 ||\n u16(localOffset + 8) !== method ||\n localNameLength !== nameLength ||\n localStart + localNameLength + u16(localOffset + 28) + compressed > directoryOffset\n )\n return rejected(\"malformed\");\n\n try {\n if (names.decode(archive.subarray(localStart, localStart + localNameLength)) !== name)\n return rejected(\"malformed\");\n } catch {\n return rejected(\"name\");\n }\n if (name === \"manifest.json\") manifest = true;\n declaredBytes += declared;\n if (declaredBytes > MAX_DECLARED_BYTES) return rejected(\"limit\");\n offset += 46 + nameLength + extraLength + entryCommentLength;\n }\n if (offset !== limit) return rejected(\"malformed\");\n if (!manifest) return rejected(\"manifest\");\n\n return { _tag: \"Accepted\", facts: { entries, declaredBytes } };\n};\n","import { Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { type ClientError, ExtensionError } from \"./Errors.ts\";\nimport { inspectExtensionArchive } from \"./internal/extension/Archive.ts\";\nimport { ExtensionReference, Identifier } from \"./References.ts\";\nimport { SafeFilename } from \"./Transfers.ts\";\n\nconst Timestamp = Schema.String.check(Schema.isMaxLength(64));\n\n/** The provider documents a 100 MB archive; a caller may request less, never more. */\nconst MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;\n\nconst ProviderExtension = Schema.Struct({\n id: Identifier,\n projectId: Identifier,\n fileName: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1024))),\n createdAt: Schema.optionalKey(Timestamp),\n updatedAt: Schema.optionalKey(Timestamp),\n});\n\n/** Only fields the provider actually returned are reported; absence is never invented. */\nexport class ExtensionMetadata extends Schema.Class<ExtensionMetadata>(\n \"BrowserbaseExtensionMetadata\",\n)({\n reference: ExtensionReference,\n fileName: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1024))),\n createdAt: Schema.optionalKey(Timestamp),\n updatedAt: Schema.optionalKey(Timestamp),\n}) {}\n\n/** Registration evidence is what this package inspected, not a provider load receipt. */\nexport class ExtensionRegistration extends Schema.Class<ExtensionRegistration>(\n \"BrowserbaseExtensionRegistration\",\n)({\n reference: ExtensionReference,\n archiveBytes: Schema.Natural,\n entries: Schema.Natural,\n declaredBytes: Schema.Natural,\n}) {}\n\nexport interface ExtensionUploadOptions {\n /** Portable basename sent with the part; defaults to `extension.zip`. */\n readonly filename?: string;\n readonly maxBytes?: number;\n readonly timeoutMillis?: number;\n}\n\nconst Upload = Schema.Struct({\n filename: Schema.optionalKey(\n SafeFilename.check(Schema.makeFilter((value) => value.toLowerCase().endsWith(\".zip\"))),\n ),\n maxBytes: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: MAX_ARCHIVE_BYTES })),\n ),\n timeoutMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 600_000 })),\n ),\n});\n\nconst fromClient = (operation: ExtensionError[\"operation\"], error: ClientError): ExtensionError =>\n ExtensionError.make({\n operation,\n reason: error.reason,\n ...(error.outcome === undefined ? {} : { outcome: error.outcome }),\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis }),\n });\n\nconst configuration = (operation: ExtensionError[\"operation\"]) =>\n ExtensionError.make({ operation, reason: \"configuration\", outcome: \"undispatched\" });\n\nconst malformed = (operation: ExtensionError[\"operation\"], mutation = false) =>\n ExtensionError.make({\n operation,\n reason: \"malformed\",\n ...(mutation ? { outcome: \"unknown\" as const } : {}),\n });\n\n/**\n * A provisioned extension is a durable project resource selected at launch, never uploaded\n * again on connect. The archive is inspected before transport; loading remains the provider's.\n */\nexport class BrowserbaseExtensions extends Context.Service<\n BrowserbaseExtensions,\n {\n readonly register: (\n archive: Uint8Array,\n options?: ExtensionUploadOptions,\n ) => Effect.Effect<ExtensionRegistration, ExtensionError>;\n readonly retrieve: (\n reference: ExtensionReference,\n ) => Effect.Effect<ExtensionMetadata, ExtensionError>;\n readonly delete: (reference: ExtensionReference) => Effect.Effect<void, ExtensionError>;\n }\n>()(\"effect-browserbase/Extensions\") {\n static readonly layer: Layer.Layer<BrowserbaseExtensions, never, BrowserbaseClient> =\n Layer.effect(\n BrowserbaseExtensions,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const validate = Effect.fnUntraced(function* (\n reference: ExtensionReference,\n operation: ExtensionError[\"operation\"],\n ) {\n const ref = yield* Schema.decodeEffect(ExtensionReference)(reference, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(operation)));\n\n if (ref.projectId !== client.projectId)\n return yield* ExtensionError.make({\n operation,\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n return ref;\n });\n\n const register = Effect.fn(\"BrowserbaseExtensions.register\")(function* (\n archive: Uint8Array,\n options: ExtensionUploadOptions = {},\n ) {\n const value = yield* Schema.decodeEffect(Upload)(options, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"extension-register\")));\n\n if (!(archive instanceof Uint8Array)) return yield* configuration(\"extension-register\");\n const maxBytes = value.maxBytes ?? MAX_ARCHIVE_BYTES;\n\n if (archive.byteLength < 1 || archive.byteLength > maxBytes)\n return yield* ExtensionError.make({\n operation: \"extension-archive\",\n reason: \"limit\",\n outcome: \"undispatched\",\n });\n\n // Inspect and send the same immutable bytes: a caller cannot swap the\n // archive between its manifest check and the multipart encoding.\n const owned = new Uint8Array(archive);\n const inspected = inspectExtensionArchive(owned);\n\n if (inspected._tag === \"Rejected\") {\n return yield* ExtensionError.make({\n operation: \"extension-archive\",\n reason:\n inspected.reason === \"limit\"\n ? \"limit\"\n : inspected.reason === \"name\"\n ? \"unsafe-filename\"\n : \"configuration\",\n outcome: \"undispatched\",\n });\n }\n\n const raw = yield* client\n .upload(\n \"/v1/extensions\",\n {\n field: \"file\",\n filename: value.filename ?? \"extension.zip\",\n mediaType: \"application/zip\",\n bytes: owned,\n },\n {\n maxBytes,\n ...(value.timeoutMillis === undefined\n ? {}\n : { timeoutMillis: value.timeoutMillis }),\n },\n )\n .pipe(Effect.mapError((error) => fromClient(\"extension-register\", error)));\n\n const created = yield* Schema.decodeUnknownEffect(ProviderExtension)(raw).pipe(\n Effect.mapError(() => malformed(\"extension-register\", true)),\n );\n\n if (created.projectId !== client.projectId)\n return yield* malformed(\"extension-register\", true);\n\n return ExtensionRegistration.make({\n reference: ExtensionReference.make({\n provider: \"browserbase\",\n projectId: client.projectId,\n extensionId: created.id,\n }),\n archiveBytes: owned.byteLength,\n entries: inspected.facts.entries,\n declaredBytes: inspected.facts.declaredBytes,\n });\n });\n\n const retrieve = Effect.fn(\"BrowserbaseExtensions.retrieve\")(function* (\n reference: ExtensionReference,\n ) {\n const ref = yield* validate(reference, \"extension-retrieve\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/extensions/${encodeURIComponent(ref.extensionId)}`)\n .pipe(Effect.mapError((error) => fromClient(\"extension-retrieve\", error)));\n\n const value = yield* Schema.decodeUnknownEffect(ProviderExtension)(raw).pipe(\n Effect.mapError(() => malformed(\"extension-retrieve\")),\n );\n\n if (value.id !== ref.extensionId || value.projectId !== ref.projectId)\n return yield* malformed(\"extension-retrieve\");\n\n return ExtensionMetadata.make({\n reference: ref,\n ...(value.fileName === undefined ? {} : { fileName: value.fileName }),\n ...(value.createdAt === undefined ? {} : { createdAt: value.createdAt }),\n ...(value.updatedAt === undefined ? {} : { updatedAt: value.updatedAt }),\n });\n });\n\n const remove = Effect.fn(\"BrowserbaseExtensions.delete\")(function* (\n reference: ExtensionReference,\n ) {\n const ref = yield* validate(reference, \"extension-delete\");\n\n yield* client\n .noContent(\"DELETE\", `/v1/extensions/${encodeURIComponent(ref.extensionId)}`)\n .pipe(Effect.mapError((error) => fromClient(\"extension-delete\", error)));\n });\n\n return BrowserbaseExtensions.of({ register, retrieve, delete: remove });\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AM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;IACtE,GAAI,MAAM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;GACxE,CAAC;EACH,CAAC;EAED,MAAM,SAAS,OAAO,GAAG,8BAA8B,CAAC,CAAC,WACvD,WACA;GACA,MAAM,MAAM,OAAO,SAAS,WAAW,kBAAkB;GAEzD,OAAO,OACJ,UAAU,UAAU,kBAAkB,mBAAmB,IAAI,WAAW,GAAG,CAAC,CAC5E,KAAK,OAAO,UAAU,UAAU,WAAW,oBAAoB,KAAK,CAAC,CAAC;EAC3E,CAAC;EAED,OAAO,sBAAsB,GAAG;GAAE;GAAU;GAAU,QAAQ;EAAO,CAAC;CACxE,CAAC,CACH;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Resource-DBksC4zB.mjs","names":[],"sources":["../src/internal/http/Resource.ts"],"sourcesContent":["import { Effect, Schema } from \"effect\";\n\nimport type { BrowserbaseClient, ClientMethod } from \"../../Client.ts\";\nimport type { ClientError } from \"../../Errors.ts\";\n\ntype Reason = ClientError[\"reason\"];\ntype Outcome = NonNullable<ClientError[\"outcome\"]>;\n\nexport interface RequestFailure<Operation extends string> {\n readonly operation: Operation;\n readonly reason: Reason;\n readonly outcome?: Outcome;\n readonly status?: number;\n readonly retryAfterMillis?: number;\n}\n\n/**\n * The shared shape of every control-plane resource: strict input decoding, tolerant reply\n * decoding, and one mapping from transport failures into the resource's own error.\n */\nexport const resource = <E extends { readonly operation: string }>(\n client: BrowserbaseClient[\"Service\"],\n make: (failure: RequestFailure<E[\"operation\"]>) => E,\n) => {\n type Operation = E[\"operation\"];\n\n const fromClient = (operation: Operation) => (error: ClientError) =>\n make({\n operation,\n reason: error.reason,\n ...(error.outcome === undefined ? {} : { outcome: error.outcome }),\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis }),\n });\n\n const configuration = (operation: Operation) =>\n make({ operation, reason: \"configuration\", outcome: \"undispatched\" });\n\n const malformed = (operation: Operation, mutation: boolean) =>\n make({ operation, reason: \"malformed\", ...(mutation ? { outcome: \"unknown\" } : {}) });\n\n /** Rejects unknown or invalid caller input before any request is built. */\n const input = <A>(\n schema: Schema.Codec<A, unknown, never, never>,\n value: unknown,\n operation: Operation,\n ): Effect.Effect<A, E> =>\n Schema.decodeUnknownEffect(schema)(value, { onExcessProperty: \"error\" }).pipe(\n Effect.mapError(() => configuration(operation)),\n );\n\n const request = <A>(\n method: ClientMethod,\n path: string,\n reply: Schema.Codec<A, unknown, never, never>,\n operation: Operation,\n body?: Schema.Json,\n ): Effect.Effect<A, E> =>\n client.json(method, path, body).pipe(\n Effect.mapError(fromClient(operation)),\n Effect.flatMap((raw) =>\n Schema.decodeEffect(reply)(raw).pipe(\n Effect.mapError(() => malformed(operation, method !== \"GET\")),\n ),\n ),\n );\n\n const remove = (path: string, operation: Operation): Effect.Effect<void, E> =>\n client.noContent(\"DELETE\", path).pipe(Effect.mapError(fromClient(operation)));\n\n const segment = (id: string) => encodeURIComponent(id);\n\n const query = (entries: Record<string, string | number | boolean | undefined>) => {\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(entries))\n if (value !== undefined) search.set(key, String(value));\n\n return search.size === 0 ? \"\" : `?${search}`;\n };\n\n return { fromClient, configuration, malformed, input, request, remove, segment, query, make };\n};\n"],"mappings":";;;;;;AAoBA,MAAa,YACX,QACA,SACG;CAGH,MAAM,cAAc,eAA0B,UAC5C,KAAK;EACH;EACA,QAAQ,MAAM;EACd,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAChE,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D,GAAI,MAAM,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,MAAM,iBAAiB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cesContent":["import { BrowserError, Reasons, type BrowserReason } from \"effect-browser/errors\";\n\nimport type { ClientError } from \"../../Errors.ts\";\n\ntype RequestFailure = Pick<ClientError, \"reason\" | \"outcome\" | \"status\" | \"retryAfterMillis\">;\n\n/** Only control-plane reads reach this bridge, before a modeled browser action dispatches. */\nexport const browserRequestFailure = (\n operation: \"connect\" | \"reconnect\" | \"live-view\",\n error: RequestFailure,\n): BrowserError => {\n const reason = (): BrowserReason => {\n switch (error.reason) {\n case \"configuration\":\n return Reasons.Configuration.make({});\n case \"authorization\":\n return Reasons.Authorization.make({});\n case \"rate-limited\":\n return Reasons.RateLimited.make(\n error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis },\n );\n case \"not-found\":\n return Reasons.NotFound.make({});\n case \"active\":\n return Reasons.Active.make({});\n case \"disabled\":\n return Reasons.Disabled.make({});\n case \"expired\":\n return Reasons.Expired.make({});\n case \"transport\":\n return Reasons.Transport.make(error.status === undefined ? {} : { status: error.status });\n case \"timeout\":\n return Reasons.Timeout.make({});\n case \"malformed\":\n return Reasons.Malformed.make({});\n case \"unsafe-url\":\n return Reasons.UnsafeUrl.make({});\n case \"content-type\":\n return Reasons.ContentType.make({});\n // A control-plane limit carries no measured bound. Do not invent native Limit facts.\n case \"limit\":\n case \"provider\":\n return Reasons.Provider.make(error.status === undefined ? {} : { status: error.status });\n }\n };\n\n return BrowserError.make({\n operation,\n reason: reason(),\n outcome: error.outcome ?? \"undispatched\",\n });\n};\n","import { Effect, Redacted, Schema } from \"effect\";\n\nimport type { BrowserbaseClient } from \"../../Client.ts\";\nimport { ClientError } from \"../../Errors.ts\";\nimport { Identifier, type SessionReference } from \"../../References.ts\";\nimport { browserRequestFailure } from \"./RequestFailure.ts\";\n\nconst LiveUrl = Schema.String.check(\n Schema.isMaxLength(16384),\n Schema.makeFilter((value) => {\n try {\n const url = new URL(value);\n\n return (\n url.protocol === \"https:\" &&\n !url.username &&\n !url.password &&\n (url.hostname === \"browserbase.com\" || url.hostname.endsWith(\".browserbase.com\"))\n );\n } catch {\n return false;\n }\n }),\n);\n\nconst Live = Schema.Struct({\n debuggerFullscreenUrl: LiveUrl,\n pages: Schema.Array(Schema.Struct({ id: Identifier, debuggerFullscreenUrl: LiveUrl })).check(\n Schema.isMaxLength(64),\n ),\n});\n\nexport interface LiveView {\n readonly session: Redacted.Redacted<string>;\n readonly pages: ReadonlyArray<{\n readonly liveViewPageId: string;\n readonly url: Redacted.Redacted<string>;\n }>;\n /** Echo of the requested TTL, not a provider-confirmed expiration time. */\n readonly requestedTtlSeconds: number;\n}\n\n/**\n * These URLs are bearer capabilities: issuing one is an authorization step, not proof that an\n * operator took control. Redaction keeps them out of ordinary logs and model-facing values.\n */\nexport const issueLiveUrls = Effect.fnUntraced(function* (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) {\n // The pinned SDK documents an optional `expiresIn` with a 21,600 second maximum, but neither\n // it nor the published debug-route schema specifies a provider minimum. One second is this\n // adapter's positive-integer input bound, not a claim that Browserbase will accept or honor it.\n if (!Number.isSafeInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > 21600)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"configuration\",\n outcome: \"undispatched\",\n });\n if (reference.projectId !== client.projectId)\n return yield* ClientError.make({\n operation: \"provider-read\",\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n const raw = yield* client.json(\n \"GET\",\n `/v1/sessions/${encodeURIComponent(reference.sessionId)}/debug?expiresIn=${expiresInSeconds}`,\n );\n\n const value = yield* Schema.decodeUnknownEffect(Live)(raw).pipe(\n Effect.mapError(() => ClientError.make({ operation: \"provider-read\", reason: \"malformed\" })),\n );\n\n return {\n session: Redacted.make(value.debuggerFullscreenUrl),\n pages: value.pages.map((page) => ({\n liveViewPageId: page.id,\n url: Redacted.make(page.debuggerFullscreenUrl),\n })),\n requestedTtlSeconds: expiresInSeconds,\n } satisfies LiveView;\n});\n\nexport const issueLiveView = (\n client: BrowserbaseClient[\"Service\"],\n reference: SessionReference,\n expiresInSeconds: number,\n) =>\n issueLiveUrls(client, reference, expiresInSeconds).pipe(\n Effect.mapError((error) => browserRequestFailure(\"live-view\", error)),\n );\n","import { Clock, Context, Effect, Layer, Schema } from \"effect\";\n\nimport { BrowserbaseClient } from \"./Client.ts\";\nimport { type ClientError, SessionError } from \"./Errors.ts\";\nimport { issueLiveUrls, type LiveView } from \"./internal/browser/LiveView.ts\";\nexport type { LiveView } from \"./internal/browser/LiveView.ts\";\nimport { SessionReference } from \"./References.ts\";\nimport {\n ProviderSession,\n SessionMetadata,\n SessionStatus,\n isTerminalSessionStatus,\n} from \"./SessionData.ts\";\nexport { SessionMetadata, SessionStatus, isTerminalSessionStatus } from \"./SessionData.ts\";\n\nexport const SessionListQuery = Schema.Struct({\n status: Schema.optionalKey(SessionStatus),\n q: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(2048))),\n});\n\nexport type SessionListQuery = typeof SessionListQuery.Type;\n\nexport const SessionWaitOptions = Schema.Struct({\n timeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 600000 })),\n pollIntervalMillis: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 25, maximum: 5000 })),\n ),\n});\n\nexport type SessionWaitOptions = typeof SessionWaitOptions.Type;\n\nconst Millis = Schema.Finite;\n\n/**\n * One CDP-level log entry. Protocol payloads are present only when requested: they carry\n * page content, cookies and typed input, so they are host evidence, never model input.\n */\nexport class SessionLogEntry extends Schema.Class<SessionLogEntry>(\"BrowserbaseSessionLogEntry\")({\n method: Schema.String.check(Schema.isMaxLength(256)),\n pageId: Schema.Int,\n frameId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n loaderId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n timestamp: Schema.optionalKey(Millis),\n requestTimestamp: Schema.optionalKey(Millis),\n responseTimestamp: Schema.optionalKey(Millis),\n params: Schema.optionalKey(Schema.Json),\n result: Schema.optionalKey(Schema.Json),\n}) {}\n\nconst ProviderLog = Schema.Struct({\n method: SessionLogEntry.fields.method,\n pageId: Schema.Int,\n sessionId: Schema.String,\n frameId: SessionLogEntry.fields.frameId,\n loaderId: SessionLogEntry.fields.loaderId,\n timestamp: Schema.optionalKey(Millis),\n request: Schema.optionalKey(\n Schema.Struct({\n params: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n response: Schema.optionalKey(\n Schema.Struct({\n result: Schema.optionalKey(Schema.Json),\n timestamp: Schema.optionalKey(Millis),\n }),\n ),\n});\n\nexport interface SessionLogOptions {\n /** Include CDP `params`/`result` payloads. Off by default; see `SessionLogEntry`. */\n readonly includePayloads?: boolean;\n}\n\nconst now = Clock.monotonicTimeNanos.pipe(Effect.map((value) => Number(value) / 1000000));\n\nconst fromClient = (operation: SessionError[\"operation\"], error: ClientError): SessionError =>\n SessionError.make({\n operation,\n reason: error.reason,\n ...(error.outcome === undefined ? {} : { outcome: error.outcome }),\n ...(error.status === undefined ? {} : { status: error.status }),\n ...(error.retryAfterMillis === undefined ? {} : { retryAfterMillis: error.retryAfterMillis }),\n });\n\nconst malformed = (operation: SessionError[\"operation\"], mutation = false) =>\n SessionError.make({\n operation,\n reason: \"malformed\",\n ...(mutation ? { outcome: \"unknown\" as const } : {}),\n });\n\nconst configuration = (operation: SessionError[\"operation\"]) =>\n SessionError.make({ operation, reason: \"configuration\", outcome: \"undispatched\" });\n\n/** Passive inspection never releases a remote session. Release is a separate explicit mutation. */\nexport class BrowserbaseSessions extends Context.Service<\n BrowserbaseSessions,\n {\n readonly retrieve: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly list: (\n query?: SessionListQuery,\n ) => Effect.Effect<ReadonlyArray<SessionMetadata>, SessionError>;\n readonly requestRelease: (\n reference: SessionReference,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitForTerminal: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n readonly waitUntilRunning: (\n reference: SessionReference,\n options: SessionWaitOptions,\n ) => Effect.Effect<SessionMetadata, SessionError>;\n /** Session logs, bounded by the 1 MiB control-plane reply limit (`reason: \"limit\"`). */\n readonly logs: (\n reference: SessionReference,\n options?: SessionLogOptions,\n ) => Effect.Effect<ReadonlyArray<SessionLogEntry>, SessionError>;\n /**\n * Redacted Live View URLs for any session in the project, owned or not. Issuing a URL\n * grants view and input access to whoever holds it; it does not pause automation.\n */\n readonly liveUrls: (\n reference: SessionReference,\n expiresInSeconds?: number,\n ) => Effect.Effect<LiveView, SessionError>;\n }\n>()(\"effect-browserbase/Sessions\") {\n static readonly layer: Layer.Layer<BrowserbaseSessions, never, BrowserbaseClient> = Layer.effect(\n BrowserbaseSessions,\n Effect.gen(function* () {\n const client = yield* BrowserbaseClient;\n\n const validate = Effect.fnUntraced(function* (\n reference: SessionReference,\n operation: SessionError[\"operation\"],\n ) {\n const ref = yield* Schema.decodeEffect(SessionReference)(reference, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(operation)));\n\n if (ref.projectId !== client.projectId)\n return yield* SessionError.make({\n operation,\n reason: \"authorization\",\n outcome: \"undispatched\",\n });\n\n return ref;\n });\n\n const decode = Effect.fnUntraced(function* (\n raw: unknown,\n operation: SessionError[\"operation\"],\n expected?: SessionReference,\n mutation: boolean = false,\n ) {\n const value = yield* Schema.decodeUnknownEffect(ProviderSession)(raw).pipe(\n Effect.mapError(() => malformed(operation, mutation)),\n );\n\n if (\n value.projectId !== client.projectId ||\n (expected !== undefined &&\n (value.id !== expected.sessionId || value.projectId !== expected.projectId))\n )\n return yield* malformed(operation, mutation);\n const { id, projectId, ...metadata } = value;\n\n return SessionMetadata.make({\n reference: SessionReference.make({ provider: \"browserbase\", projectId, sessionId: id }),\n ...metadata,\n });\n });\n\n const read = Effect.fnUntraced(function* (reference: SessionReference, deadline?: number) {\n const ref = yield* validate(reference, \"session-retrieve\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, undefined, deadline)\n .pipe(Effect.mapError((error) => fromClient(\"session-retrieve\", error)));\n\n return yield* decode(raw, \"session-retrieve\", ref);\n });\n\n const retrieve = Effect.fn(\"BrowserbaseSessions.retrieve\")(function* (\n reference: SessionReference,\n ) {\n return yield* read(reference);\n });\n\n const list = Effect.fn(\"BrowserbaseSessions.list\")(function* (query: SessionListQuery = {}) {\n const checked = yield* Schema.decodeEffect(SessionListQuery)(query, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-list\")));\n\n const search = new URLSearchParams();\n\n if (checked.status !== undefined) search.set(\"status\", checked.status);\n if (checked.q !== undefined) search.set(\"q\", checked.q);\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions${search.size === 0 ? \"\" : `?${search}`}`)\n .pipe(Effect.mapError((error) => fromClient(\"session-list\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderSession).check(Schema.isMaxLength(1024)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-list\")));\n\n if (new Set(rows.map((row) => row.id)).size !== rows.length)\n return yield* malformed(\"session-list\");\n const output: SessionMetadata[] = [];\n\n for (const row of rows) output.push(yield* decode(row, \"session-list\"));\n\n return output;\n });\n\n const requestRelease = Effect.fn(\"BrowserbaseSessions.requestRelease\")(function* (\n reference: SessionReference,\n ) {\n const ref = yield* validate(reference, \"session-release\");\n\n const raw = yield* client\n .json(\"POST\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}`, {\n projectId: ref.projectId,\n status: \"REQUEST_RELEASE\",\n })\n .pipe(Effect.mapError((error) => fromClient(\"session-release\", error)));\n\n return yield* decode(raw, \"session-release\", ref, true);\n });\n\n const wait = Effect.fnUntraced(function* (\n reference: SessionReference,\n options: SessionWaitOptions,\n untilRunning: boolean,\n ) {\n const bounds = yield* Schema.decodeEffect(SessionWaitOptions)(options, {\n onExcessProperty: \"error\",\n }).pipe(Effect.mapError(() => configuration(\"session-wait\")));\n\n const deadline = (yield* now) + bounds.timeoutMillis;\n\n for (;;) {\n const remaining = deadline - (yield* now);\n\n if (remaining <= 0)\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"timeout\" });\n\n // The deadline bounds the provider read too, not just sleeps between reads.\n const metadata = yield* read(reference, deadline).pipe(\n Effect.timeoutOrElse({\n duration: remaining,\n orElse: () =>\n Effect.fail(SessionError.make({ operation: \"session-wait\", reason: \"timeout\" })),\n }),\n );\n\n if (\n untilRunning ? metadata.status === \"RUNNING\" : isTerminalSessionStatus(metadata.status)\n )\n return metadata;\n if (untilRunning && isTerminalSessionStatus(metadata.status))\n return yield* SessionError.make({ operation: \"session-wait\", reason: \"expired\" });\n yield* Effect.sleep(\n Math.max(0, Math.min(bounds.pollIntervalMillis ?? 250, deadline - (yield* now))),\n );\n }\n });\n\n const logs = Effect.fn(\"BrowserbaseSessions.logs\")(function* (\n reference: SessionReference,\n options: SessionLogOptions = {},\n ) {\n const ref = yield* validate(reference, \"session-logs\");\n\n const raw = yield* client\n .json(\"GET\", `/v1/sessions/${encodeURIComponent(ref.sessionId)}/logs`)\n .pipe(Effect.mapError((error) => fromClient(\"session-logs\", error)));\n\n const rows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ProviderLog).check(Schema.isMaxLength(100_000)),\n )(raw).pipe(Effect.mapError(() => malformed(\"session-logs\")));\n\n if (rows.some((row) => row.sessionId !== ref.sessionId))\n return yield* malformed(\"session-logs\");\n\n return rows.map((row) =>\n SessionLogEntry.make({\n method: row.method,\n pageId: row.pageId,\n ...(row.frameId === undefined ? {} : { frameId: row.frameId }),\n ...(row.loaderId === undefined ? {} : { loaderId: row.loaderId }),\n ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),\n ...(row.request?.timestamp === undefined\n ? {}\n : { requestTimestamp: row.request.timestamp }),\n ...(row.response?.timestamp === undefined\n ? {}\n : { responseTimestamp: row.response.timestamp }),\n ...(options.includePayloads === true && row.request?.params !== undefined\n ? { params: row.request.params }\n : {}),\n ...(options.includePayloads === true && row.response?.result !== undefined\n ? { result: row.response.result }\n : {}),\n }),\n );\n });\n\n const liveUrls = Effect.fn(\"BrowserbaseSessions.liveUrls\")(function* (\n reference: SessionReference,\n expiresInSeconds: number = 300,\n ) {\n const ref = yield* validate(reference, \"session-live-view\");\n\n return yield* issueLiveUrls(client, ref, expiresInSeconds).pipe(\n Effect.mapError((error) => fromClient(\"session-live-view\", error)),\n );\n });\n\n return BrowserbaseSessions.of({\n logs,\n liveUrls,\n retrieve,\n list,\n requestRelease,\n waitForTerminal: (ref, options) => wait(ref, options, false),\n waitUntilRunning: (ref, options) => wait(ref, options, true),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,yBACX,WACA,UACiB;CACjB,MAAM,eAA8B;EAClC,QAAQ,MAAM,QAAd;GACE,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,iBACH,OAAO,QAAQ,cAAc,KAAK,CAAC,CAAC;GACtC,KAAK,gBACH,OAAO,QAAQ,YAAY,KACzB,MAAM,qBAAqB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,MAAM,iBAAiB,CACzF;GACF,KAAK,aACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,UACH,OAAO,QAAQ,OAAO,KAAK,CAAC,CAAC;GAC/B,KAAK,YACH,OAAO,QAAQ,SAAS,KAAK,CAAC,CAAC;GACjC,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KAAK,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO,CAAC;GAC1F,KAAK,WACH,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC;GAChC,KAAK,aACH,OAAO,QAAQ,UAAU,KA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