bitsnap-react 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -6
- package/dist/CartProvider-HXLGQ4EX.mjs +2 -0
- package/dist/CartProvider-OHHYOMSG.js +2 -0
- package/dist/CartProvider-OHHYOMSG.js.map +1 -0
- package/dist/analytics.d.mts +22 -5
- package/dist/analytics.d.ts +22 -5
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.d.mts +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-VM6JEJFZ.js → chunk-3Z6VNXBP.js} +2 -2
- package/dist/chunk-3Z6VNXBP.js.map +1 -0
- package/dist/{chunk-RA452LXZ.mjs → chunk-43IIYJ6J.mjs} +2 -2
- package/dist/{chunk-SLLBTQTW.mjs → chunk-6D3OORMK.mjs} +2 -2
- package/dist/chunk-ADYVTMGH.mjs +2 -0
- package/dist/chunk-ADYVTMGH.mjs.map +1 -0
- package/dist/{chunk-FHDFLSPW.js → chunk-AJNULBC3.js} +2 -2
- package/dist/chunk-AJNULBC3.js.map +1 -0
- package/dist/chunk-B32ACCW2.js +2 -0
- package/dist/chunk-B32ACCW2.js.map +1 -0
- package/dist/{chunk-SZ256RCC.mjs → chunk-DDY7IBMG.mjs} +2 -2
- package/dist/{chunk-KG6RU37U.js → chunk-DPKT6ITB.js} +3 -3
- package/dist/chunk-DPKT6ITB.js.map +1 -0
- package/dist/{chunk-VXB7LA4E.js → chunk-F46RJVWC.js} +2 -2
- package/dist/chunk-F46RJVWC.js.map +1 -0
- package/dist/{chunk-3IMJALBX.js → chunk-F6GQLKA6.js} +2 -2
- package/dist/chunk-F6GQLKA6.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-LZE2E4TE.mjs → chunk-JXCHRSPW.mjs} +3 -3
- package/dist/{chunk-LZE2E4TE.mjs.map → chunk-JXCHRSPW.mjs.map} +1 -1
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-RLEC25JI.mjs +2 -0
- package/dist/chunk-RLEC25JI.mjs.map +1 -0
- package/dist/{chunk-V4U2PTKN.js → chunk-RVILRUW3.js} +2 -2
- package/dist/chunk-RVILRUW3.js.map +1 -0
- package/dist/{chunk-HKVMSMDF.mjs → chunk-T2OUOO4X.mjs} +2 -2
- package/dist/{chunk-CO2P4FR5.js → chunk-VIII45AC.js} +2 -2
- package/dist/chunk-VIII45AC.js.map +1 -0
- package/dist/chunk-XIHGWNTS.js +2 -0
- package/dist/chunk-XIHGWNTS.js.map +1 -0
- package/dist/{chunk-LJWS6ZRJ.mjs → chunk-YXFJG4MF.mjs} +2 -2
- package/dist/{chunk-GN63ITLA.mjs → chunk-ZPTHK4OX.mjs} +2 -2
- package/dist/consent.d.mts +7 -0
- package/dist/consent.d.ts +7 -0
- package/dist/consent.js +4 -4
- package/dist/consent.js.map +1 -1
- package/dist/consent.mjs +4 -4
- package/dist/consent.mjs.map +1 -1
- package/dist/course.d.mts +2 -2
- package/dist/course.d.ts +2 -2
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/embed/consent.js +2 -2
- package/dist/errors.js.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{instrument-C_abZLHk.d.ts → instrument-CmxK7S4T.d.mts} +22 -5
- package/dist/{instrument-C_abZLHk.d.mts → instrument-CmxK7S4T.d.ts} +22 -5
- package/dist/internal.js.map +1 -1
- package/dist/methods-A5KGZBAM.js +2 -0
- package/dist/methods-A5KGZBAM.js.map +1 -0
- package/dist/methods-AOHKV7IN.mjs +2 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +1 -1
- package/dist/returns.d.ts +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-D_WnqwR_.d.mts → types-BnVWLcoB.d.mts} +1 -1
- package/dist/{types-BaqLJYuq.d.ts → types-i-IuN4Im.d.ts} +1 -1
- package/package.json +2 -2
- package/dist/CartProvider-XWTLBIZ5.js +0 -2
- package/dist/CartProvider-XWTLBIZ5.js.map +0 -1
- package/dist/CartProvider-ZURLJNBW.mjs +0 -2
- package/dist/chunk-3IMJALBX.js.map +0 -1
- package/dist/chunk-3UHPJ6NK.js +0 -2
- package/dist/chunk-3UHPJ6NK.js.map +0 -1
- package/dist/chunk-CO2P4FR5.js.map +0 -1
- package/dist/chunk-E6QVQEGZ.mjs +0 -2
- package/dist/chunk-E6QVQEGZ.mjs.map +0 -1
- package/dist/chunk-FHDFLSPW.js.map +0 -1
- package/dist/chunk-KG6RU37U.js.map +0 -1
- package/dist/chunk-QZJGNLCZ.js +0 -2
- package/dist/chunk-QZJGNLCZ.js.map +0 -1
- package/dist/chunk-V4U2PTKN.js.map +0 -1
- package/dist/chunk-VM6JEJFZ.js.map +0 -1
- package/dist/chunk-VXB7LA4E.js.map +0 -1
- package/dist/chunk-XVQKEGPO.mjs +0 -2
- package/dist/chunk-XVQKEGPO.mjs.map +0 -1
- package/dist/methods-CYARZTYL.mjs +0 -2
- package/dist/methods-DAPEWVI6.js +0 -2
- package/dist/methods-DAPEWVI6.js.map +0 -1
- /package/dist/{CartProvider-ZURLJNBW.mjs.map → CartProvider-HXLGQ4EX.mjs.map} +0 -0
- /package/dist/{chunk-RA452LXZ.mjs.map → chunk-43IIYJ6J.mjs.map} +0 -0
- /package/dist/{chunk-SLLBTQTW.mjs.map → chunk-6D3OORMK.mjs.map} +0 -0
- /package/dist/{chunk-SZ256RCC.mjs.map → chunk-DDY7IBMG.mjs.map} +0 -0
- /package/dist/{chunk-HKVMSMDF.mjs.map → chunk-T2OUOO4X.mjs.map} +0 -0
- /package/dist/{chunk-LJWS6ZRJ.mjs.map → chunk-YXFJG4MF.mjs.map} +0 -0
- /package/dist/{chunk-GN63ITLA.mjs.map → chunk-ZPTHK4OX.mjs.map} +0 -0
- /package/dist/{methods-CYARZTYL.mjs.map → methods-AOHKV7IN.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/contract.ts"],"names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"AAiBO,qrBAAMA,CAAAA,CAAS,CAEpB,cAAA,CAAgB,EAAA,CAEhB,YAAA,CAAc,KAAA,CAEd,aAAA,CAAe,IAAA,CACf,aAAA,CAAe,GAAA,CACf,YAAA,CAAc,EAAA,CACd,IAAA,CAAM,GAAA,CACN,IAAA,CAAM,GAAA,CACN,YAAA,CAAc,GAAA,CACd,GAAA,CAAK,GAAA,CACL,OAAA,CAAS,EAAA,CACT,EAAA,CAAI,EAAA,CACJ,GAAA,CAAK,EAAA,CACL,MAAA,CAAQ,EAAA,CACR,MAAA,CAAQ,EAAA,CACR,SAAA,CAAW,EAAA,CAEX,QAAA,CAAU,KACZ,CAAA,CAMaC,CAAAA,CAAU,CACrB,mBAAA,CACA,YAAA,CACA,iBACF,CAAA,CAGaC,CAAAA,CAAO,CAAC,MAAA,CAAQ,MAAM,CAAA,CAGtBC,CAAAA,CAAU,CACrB,YAAA,CACA,WAAA,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* SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` and\n * `computeConsentedVisitorId` are pure but need the server secret; they are\n * server-only: the browser never calls them, so bundlers drop them.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n /**\n * The value of the first-party `bs_vid_<projectKey>` cookie (`CLIENT_ID_RE`), sent only\n * while analytics consent is granted. The collector turns it into a stable\n * `consentedVisitorId` and never stores it.\n */\n client_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\n// ---------------------------------------------------------------------------\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n\n/** POST /consent body. */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n/**\n * Decodes the value of a consent cookie (§11.3). Null when it is not base64url\n * JSON of the documented shape (`v` 1 and a boolean per category).\n */\nexport function parseConsentCookie(value: string | null | undefined): ConsentCookie | null {\n if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const json: unknown = JSON.parse(\n new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0))),\n );\n if (!isRecord(json) || json.v !== 1) return null;\n const c = json.c;\n if (!isRecord(c)) return null;\n if (\n typeof c.analytics !== \"boolean\" ||\n typeof c.marketing !== \"boolean\" ||\n typeof c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return json as unknown as ConsentCookie;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n/**\n * The `bs_vid_<projectKey>` cookie name. `projectKey` is the bare public key\n * (like `consentCookieName`): consent is per project, so is the client id.\n */\nexport function clientIdCookieName(projectKey: string): string {\n return `bs_vid_${projectKey}`;\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie: 16 random bytes, base64url without padding. */\nexport const CLIENT_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\n/**\n * Stable visitor id of a browser that granted analytics consent (contract §6).\n *\n * consented_visitor_id = \"p_\" + base64url(HMAC-SHA256(key = utf8(masterSecret),\n * msg = utf8(\"client\\n\" + clientId + \"\\n\" + projectId))).slice(0, 22)\n *\n * 24 characters; daily ids are 22, so `isConsentedVisitorId` tells them apart.\n * `clientId` is the `bs_vid_<projectKey>` cookie value and is never stored.\n */\nexport async function computeConsentedVisitorId(\n masterSecret: string,\n clientId: string,\n projectId: number | string,\n): Promise<string> {\n if (!CLIENT_ID_RE.test(clientId)) {\n throw new Error(\"clientId must be 22 base64url characters\");\n }\n const mac = await hmacSha256(\n encoder.encode(masterSecret),\n `client\\n${clientId}\\n${projectId}`,\n );\n return `p_${base64url(mac).slice(0, 22)}`;\n}\n\n/** Whether `visitorId` came from `computeConsentedVisitorId` (not a daily id). */\nexport function isConsentedVisitorId(visitorId: string): boolean {\n return visitorId.length === 24 && visitorId.startsWith(\"p_\");\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` is refused (only\n * POST /consent writes it) and `source` must fit the stream. `server` is the\n * instapay emitter: any stream, `source` must fit the stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\") return fail(\"consent_via_consent_endpoint\");\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n if (e.client_id != null) {\n if (typeof e.client_id !== \"string\" || !CLIENT_ID_RE.test(e.client_id)) {\n return fail(\"bad_client_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as p}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{o as p}from"./chunk-T2OUOO4X.mjs";import{l as g,n as d}from"./chunk-RLEC25JI.mjs";var t={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},u=[];function w(e){t={...t,...e}}function s(){return t}function P(e){t.projectID=e}function v(e){t.theme=e}function C(e){t.loginURL=e}function R(e){t.host=e}function x(e){u=e,t={...t,allowedReturnOrigins:e}}function y(){return u}import{createContext as c,useContext as m}from"react";import{jsx as r}from"react/jsx-runtime";var f=c(s()),b=({children:e,analytics:n})=>{let o=s(),i=d(o.projectID,n,"panel");return r(p,{children:r(f.Provider,{value:{...o},children:r(g,{value:i,children:r("div",{className:"bitsnap-react",children:e})})})})},L=()=>m(f);var l=(e,n)=>`bitsnap-panel-session:${encodeURIComponent(n??"https://bitsnap.pl")}:${encodeURIComponent(e)}`,a=(e,n)=>`bitsnap-panel-email:${encodeURIComponent(n??"https://bitsnap.pl")}:${encodeURIComponent(e)}`;function $(e,n){return typeof window>"u"||!e?void 0:window.localStorage.getItem(l(e,n))??void 0}function G(e,n,o,i){typeof window>"u"||!e||(window.localStorage.setItem(l(e,i),n),window.localStorage.setItem(a(e,i),o))}function k(e,n){return typeof window>"u"||!e?null:window.localStorage.getItem(a(e,n))}function E(e,n){typeof window>"u"||!e||(window.localStorage.removeItem(l(e,n)),window.localStorage.removeItem(a(e,n)))}export{w as a,s as b,P as c,v as d,C as e,R as f,x as g,y as h,b as i,L as j,$ as k,G as l,k as m,E as n};
|
|
2
|
+
//# sourceMappingURL=chunk-YXFJG4MF.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-DDY7IBMG.mjs";import{d as a}from"./chunk-43IIYJ6J.mjs";var B=["orders","order","confirmation","result","myReturns","myReturn"];function P(e){return B.includes(e)}function f(e){return e?{name:"orders"}:{name:"email"}}function C(e,n){switch(n.type){case"SESSION_EXPIRED":return P(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:n.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:n.items,note:n.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:n.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:n.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var x={email:1,code:2,orders:3,order:4,confirmation:5,result:6},_=6;function O(e){return x[e]}import{useEffect as D,useReducer as A}from"react";import{jsx as o,jsxs as L}from"react/jsx-runtime";function g({current:e}){let n=i(),r=m("stepIndicator");return o("p",{"data-bitsnap-returns-slot":"stepIndicator",className:a("text-xs",r.className),style:r.style,children:n("stepIndicator",{current:e,total:_})})}function b({panelToken:e}){let{status:n}=d("BitsnapReturns"),[r,t]=A(C,f(!1));if(D(()=>{n==="authenticated"?t({type:"AUTHENTICATED"}):n==="anonymous"&&t({type:"SESSION_EXPIRED"})},[n]),n==="exchanging"||n==="hydrating"&&e)return o(c,{});let s=O(r.name);return L("div",{className:"flex flex-col gap-4",children:[s!=null&&o(g,{current:s}),r.name==="email"&&o(E,{onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&o(p,{onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&o(S,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&o(l,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:U})=>t({type:"REVIEW",items:u,note:U})}),r.name==="confirmation"&&o(y,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&o(I,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&o(T,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&o(N,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function q(e){return o(R,{...e,children:o(b,{panelToken:e.panelAccessToken!=null&&e.panelAccessToken!==""})})}export{q as a};
|
|
2
|
+
//# sourceMappingURL=chunk-ZPTHK4OX.mjs.map
|
package/dist/consent.d.mts
CHANGED
|
@@ -69,6 +69,13 @@ type ConsentOptions = {
|
|
|
69
69
|
description?: string;
|
|
70
70
|
};
|
|
71
71
|
type BitsnapConsentApi = {
|
|
72
|
+
/**
|
|
73
|
+
* Whose choice this banner holds: `project` keeps one cookie per project key
|
|
74
|
+
* (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.
|
|
75
|
+
*/
|
|
76
|
+
readonly scope: "global" | "project";
|
|
77
|
+
/** The bare public project key the banner was started with, if any (`pk_` stripped). */
|
|
78
|
+
readonly projectKey: string | null;
|
|
72
79
|
get(): ConsentState | null;
|
|
73
80
|
/**
|
|
74
81
|
* `true` when the visitor refused `category`, also in a choice made on an older banner
|
package/dist/consent.d.ts
CHANGED
|
@@ -69,6 +69,13 @@ type ConsentOptions = {
|
|
|
69
69
|
description?: string;
|
|
70
70
|
};
|
|
71
71
|
type BitsnapConsentApi = {
|
|
72
|
+
/**
|
|
73
|
+
* Whose choice this banner holds: `project` keeps one cookie per project key
|
|
74
|
+
* (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.
|
|
75
|
+
*/
|
|
76
|
+
readonly scope: "global" | "project";
|
|
77
|
+
/** The bare public project key the banner was started with, if any (`pk_` stripped). */
|
|
78
|
+
readonly projectKey: string | null;
|
|
72
79
|
get(): ConsentState | null;
|
|
73
80
|
/**
|
|
74
81
|
* `true` when the visitor refused `category`, also in a choice made on an older banner
|
package/dist/consent.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk3UHPJ6NKjs = require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');var A=["analytics","marketing","preferences"];var Ae='script[type="text/plain"][data-bitsnap-consent]:not([data-bitsnap-queued])',Ee="iframe[data-bitsnap-consent][data-src]",oe=(e,t)=>A.includes(_nullishCoalesce(t, () => ("")))&&e[t];function Le(e){return new Promise(t=>{e.addEventListener("load",()=>t(),{once:!0}),e.addEventListener("error",()=>t(),{once:!0})})}function ie(e,t){let n=e.createElement("script");for(let{name:s,value:l}of Array.from(t.attributes))s==="type"||s==="data-bitsnap-queued"||(s==="data-type"?l==="module"&&n.setAttribute("type","module"):s==="data-src"?n.setAttribute("src",l):n.setAttribute(s,l));t.nonce&&(n.nonce=t.nonce);let i=n.hasAttribute("src");i?t.hasAttribute("async")||(n.async=!1):n.text=t.text;let p=i?Le(n):void 0;return _optionalChain([t, 'access', _2 => _2.parentNode, 'optionalAccess', _3 => _3.replaceChild, 'call', _4 => _4(n,t)]),p}function re(e,t){let n=0;try{let i=null,p=[];e.querySelectorAll(Ae).forEach(s=>{if(!oe(t,s.getAttribute("data-bitsnap-consent")))return;n++;let l=!s.hasAttribute("data-src")&&!s.hasAttribute("src");if(i||l&&p.length>0){s.setAttribute("data-bitsnap-queued",""),i=(_nullishCoalesce(i, () => (Promise.all(p).then(()=>{})))).then(()=>{try{return ie(e,s)}catch (e2){}}),p=[];return}let u=ie(e,s);u&&p.push(u)}),e.querySelectorAll(Ee).forEach(s=>{if(!oe(t,s.getAttribute("data-bitsnap-consent")))return;let l=s.getAttribute("data-src");l&&s.getAttribute("src")!==l&&(s.setAttribute("src",l),s.removeAttribute("data-src"),n++)})}catch (e3){}return n}var se="https://bitsnap.pl",ae="https://collect.bitsnap.pl";function Z(){return{version:1,theme:"auto",position:"bottom",categories:{analytics:!0,marketing:!0,preferences:!1},services:[],poweredBy:!0}}var je=["auto","light","dark"],Pe=["bottom","bottom-left","bottom-right"],_e=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;function Oe(e){return typeof e=="string"&&_e.test(e.trim())?e.trim():void 0}function Me(e){if(typeof e!="string")return;let t=e.trim();return/^(?:https?:\/\/|\/(?!\/)|#|\?)/i.test(t)?t:void 0}function ze(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)n&&typeof n.name=="string"&&A.includes(n.category)&&t.push({name:n.name,category:n.category,cookies:Array.isArray(n.cookies)?n.cookies.filter(i=>typeof i=="string"):void 0});return t}function $(...e){let t=Z();for(let n of e){if(!n||typeof n!="object")continue;typeof n.version=="number"&&n.version>=0&&(t.version=Math.floor(n.version)),je.includes(n.theme)&&(t.theme=n.theme),Pe.includes(n.position)&&(t.position=n.position);let i=Oe(n.accentColor);i&&(t.accentColor=i);let p=Me(n.privacyPolicyUrl);if(p&&(t.privacyPolicyUrl=p),n.categories&&typeof n.categories=="object")for(let s of A)typeof n.categories[s]=="boolean"&&(t.categories[s]=n.categories[s]);n.services!==void 0&&(t.services=ze(n.services)),n.texts&&typeof n.texts=="object"&&(t.texts=n.texts)}return t}async function ce(e,t,n=3e3){if(typeof fetch!="function")return null;let i=typeof AbortController=="function"?new AbortController:void 0,p=setTimeout(()=>_optionalChain([i, 'optionalAccess', _5 => _5.abort, 'call', _6 => _6()]),n);try{let s=await fetch(`${e.replace(/\/+$/,"")}/api/consent/config?key=${encodeURIComponent(t)}`,{signal:_optionalChain([i, 'optionalAccess', _7 => _7.signal]),credentials:"omit"});if(!s.ok)return null;let l=await s.json();if(!l||typeof l!="object")return null;let u=l.config&&typeof l.config=="object"?l.config:null,g=l.enabled!==!1;return u||!g?{enabled:g,config:u}:null}catch (e4){return null}finally{clearTimeout(p)}}var le="bitsnap_consent";function de(e,t){return t==="project"&&e?`${le}_${e.replace(/[^A-Za-z0-9_-]/g,"_")}`:le}function Ue(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function De(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");return atob(t+"=".repeat((4-t.length%4)%4))}function Be(e){return Ue(JSON.stringify({v:1,id:e.id,ts:e.ts,bv:e.bv,c:e.c}))}function $e(e){try{let t=JSON.parse(De(e));return!t||t.v!==1||typeof t.id!="string"||t.id===""||typeof t.ts!="number"||typeof t.bv!="number"||!t.c||typeof t.c.analytics!="boolean"||typeof t.c.marketing!="boolean"||typeof t.c.preferences!="boolean"?null:{id:t.id,ts:t.ts,bv:t.bv,c:{analytics:t.c.analytics,marketing:t.c.marketing,preferences:t.c.preferences}}}catch (e5){return null}}function He(e,t,n){return`${e}=${Be(t)}; Max-Age=31536000; Path=/; SameSite=Lax`+(n?"; Secure":"")}function Re(e){return e.split(";").map(t=>t.split("=")[0].trim()).filter(Boolean)}function Ie(e,t){for(let n of e.split(";")){let i=n.indexOf("=");if(i!==-1&&n.slice(0,i).trim()===t)return $e(n.slice(i+1).trim())}return null}function pe(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch (e6){}let e="";for(let t=0;t<32;t++)e+=Math.floor(Math.random()*16).toString(16);return e}function fe(e,t){try{return Ie(e.cookie,t)}catch (e7){return null}}function ue(e,t,n){try{e.cookie=He(t,n,_optionalChain([e, 'access', _8 => _8.location, 'optionalAccess', _9 => _9.protocol])==="https:")}catch (e8){}}function ge(e,t){try{e.cookie=`${t}=; Max-Age=0; Path=/; SameSite=Lax`}catch (e9){}}function Ne(e){if(!e||/^[\d.]+$/.test(e)||e.includes(":"))return[];let t=e.split("."),n=[];for(let i=0;i<=t.length-2;i++)n.push(t.slice(i).join("."));return n}function V(e,t,n){try{let i=t.filter(u=>n.includes(u.category)).flatMap(u=>_nullishCoalesce(u.cookies, () => ([])));if(i.length===0)return;let p=Re(e.cookie),s=new Set;for(let u of i)if(u.endsWith("*")){let g=u.slice(0,-1);for(let f of p)f.startsWith(g)&&s.add(f)}else s.add(u);let l=Ne(_nullishCoalesce(_optionalChain([e, 'access', _10 => _10.location, 'optionalAccess', _11 => _11.hostname]), () => ("")));for(let u of s){let g=`${encodeURIComponent(u)}=; Max-Age=0; Path=/`;e.cookie=g;for(let f of l)e.cookie=`${g}; Domain=${f}`,e.cookie=`${g}; Domain=.${f}`}}catch (e10){}}var Ke={ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied",functionality_storage:"denied",personalization_storage:"denied",security_storage:"granted",wait_for_update:500},M=e=>e?"granted":"denied";function Q(e){return{analytics_storage:M(e.analytics),ad_storage:M(e.marketing),ad_user_data:M(e.marketing),ad_personalization:M(e.marketing),functionality_storage:M(e.preferences),personalization_storage:M(e.preferences)}}function Ge(e,t){return t==="off"?!1:t==="on"||typeof e.gtag=="function"||Array.isArray(e.dataLayer)}function We(e){if(typeof e.gtag=="function")return e.gtag;let t=e.dataLayer=e.dataLayer||[],n=function(){t.push(arguments)};return e.gtag=n,n}function ye(e,t){if(!Ge(e,t))return null;let n=We(e);return{setDefault:()=>n("consent","default",{...Ke}),update:i=>n("consent","update",Q(i))}}var ee={pl:{title:"Szanujemy Twoj\u0105 prywatno\u015B\u0107",description:"U\u017Cywamy plik\xF3w cookie, aby strona dzia\u0142a\u0142a poprawnie. Za Twoj\u0105 zgod\u0105 wykorzystujemy je te\u017C do statystyk, personalizacji i reklam. Mo\u017Cesz zaakceptowa\u0107 wszystkie, odrzuci\u0107 wszystkie albo wybra\u0107, na co si\u0119 zgadzasz.",acceptAll:"Akceptuj wszystkie",rejectAll:"Odrzu\u0107 wszystkie",settings:"Ustawienia",save:"Zapisz wyb\xF3r",close:"Zamknij",necessaryTitle:"Niezb\u0119dne",necessaryDescription:"Potrzebne do dzia\u0142ania strony: koszyk, zapami\u0119tanie Twojego wyboru, bezpiecze\u0144stwo. Nie mo\u017Cna ich wy\u0142\u0105czy\u0107.",analyticsTitle:"Statystyki",analyticsDescription:"Pomagaj\u0105 nam zrozumie\u0107, jak odwiedzaj\u0105cy korzystaj\u0105 ze strony, \u017Ceby\u015Bmy mogli j\u0105 ulepsza\u0107.",marketingTitle:"Marketing",marketingDescription:"Pozwalaj\u0105 mierzy\u0107 skuteczno\u015B\u0107 reklam i pokazywa\u0107 Ci oferty dopasowane do zainteresowa\u0144.",preferencesTitle:"Preferencje",preferencesDescription:"Zapami\u0119tuj\u0105 Twoje ustawienia, na przyk\u0142ad j\u0119zyk czy wygl\u0105d strony.",poweredBy:"Powered by"},en:{title:"We value your privacy",description:"We use cookies to make this site work. With your consent we also use them for statistics, personalization and ads. You can accept all, reject all, or choose what you agree to.",acceptAll:"Accept all",rejectAll:"Reject all",settings:"Settings",save:"Save choices",close:"Close",necessaryTitle:"Necessary",necessaryDescription:"Needed for the site to work: the cart, remembering your choice, security. They cannot be turned off.",analyticsTitle:"Analytics",analyticsDescription:"Help us understand how visitors use the site, so we can improve it.",marketingTitle:"Marketing",marketingDescription:"Measure how well ads work and show you offers that match your interests.",preferencesTitle:"Preferences",preferencesDescription:"Remember your settings, such as language or how the site looks.",poweredBy:"Powered by"}},me={pl:{privacy:"Polityka prywatno\u015Bci",services:"Us\u0142ugi",always:"Zawsze aktywne"},en:{privacy:"Privacy policy",services:"Services",always:"Always on"}};function F(e,t){return e==="pl"||e==="en"?e:/^pl\b/i.test(_nullishCoalesce(t, () => ("")))?"pl":"en"}function X(e,t){let n={...ee[e]},i=_optionalChain([t, 'optionalAccess', _12 => _12[e]]);if(i)for(let p of Object.keys(n)){let s=i[p];typeof s=="string"&&s.trim()!==""&&(n[p]=s)}return n}function Fe(e){let t=e.replace("#","");t.length===3&&(t=t.replace(/./g,"$&$&"));let n=parseInt(t,16);return[n>>16&255,n>>8&255,n&255]}function Ce(e){let[t,n,i]=Fe(e).map(p=>{let s=p/255;return s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4)});return .2126*t+.7152*n+.0722*i}function q(e,t){let[n,i]=[Ce(e),Ce(t)].sort((p,s)=>s-p);return(n+.05)/(i+.05)}function he(e){return q(e,"#ffffff")>=q(e,"#111111")?"#ffffff":"#111111"}var J={light:{bg:"#ffffff",fg:"#14171c",muted:"#495260",border:"#c9ced6",off:"#6b7280",thumb:"#ffffff",accent:"#1d4ed8",onAccent:"#ffffff",link:"#1d4ed8"},dark:{bg:"#171a20",fg:"#f1f3f6",muted:"#b7beca",border:"#3a404b",off:"#8b93a1",thumb:"#171a20",accent:"#8ab4ff",onAccent:"#0b1220",link:"#9dc0ff"}},be=e=>`--bg:${e.bg};--fg:${e.fg};--muted:${e.muted};--border:${e.border};--off:${e.off};--thumb:${e.thumb};--accent:${e.accent};--on-accent:${e.onAccent};--link:${e.link};--focus:${e.accent}`,xe=`
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkXIHGWNTSjs = require('./chunk-XIHGWNTS.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');var A=["analytics","marketing","preferences"];var Ee='script[type="text/plain"][data-bitsnap-consent]:not([data-bitsnap-queued])',Ae="iframe[data-bitsnap-consent][data-src]",ce=(e,n)=>A.includes(_nullishCoalesce(n, () => ("")))&&e[n];function Se(e){return new Promise(n=>{e.addEventListener("load",()=>n(),{once:!0}),e.addEventListener("error",()=>n(),{once:!0})})}function le(e,n){let t=e.createElement("script");for(let{name:s,value:l}of Array.from(n.attributes))s==="type"||s==="data-bitsnap-queued"||(s==="data-type"?l==="module"&&t.setAttribute("type","module"):s==="data-src"?t.setAttribute("src",l):t.setAttribute(s,l));n.nonce&&(t.nonce=n.nonce);let r=t.hasAttribute("src");r?n.hasAttribute("async")||(t.async=!1):t.text=n.text;let p=r?Se(t):void 0;return _optionalChain([n, 'access', _2 => _2.parentNode, 'optionalAccess', _3 => _3.replaceChild, 'call', _4 => _4(t,n)]),p}function de(e,n){let t=0;try{let r=null,p=[];e.querySelectorAll(Ee).forEach(s=>{if(!ce(n,s.getAttribute("data-bitsnap-consent")))return;t++;let l=!s.hasAttribute("data-src")&&!s.hasAttribute("src");if(r||l&&p.length>0){s.setAttribute("data-bitsnap-queued",""),r=(_nullishCoalesce(r, () => (Promise.all(p).then(()=>{})))).then(()=>{try{return le(e,s)}catch (e2){}}),p=[];return}let C=le(e,s);C&&p.push(C)}),e.querySelectorAll(Ae).forEach(s=>{if(!ce(n,s.getAttribute("data-bitsnap-consent")))return;let l=s.getAttribute("data-src");l&&s.getAttribute("src")!==l&&(s.setAttribute("src",l),s.removeAttribute("data-src"),t++)})}catch (e3){}return t}var pe="https://bitsnap.pl",fe="https://collect.bitsnap.pl";function V(){return{version:1,theme:"auto",position:"bottom",categories:{analytics:!0,marketing:!0,preferences:!1},services:[],poweredBy:!0}}var Le=["auto","light","dark"],je=["bottom","bottom-left","bottom-right"],Pe=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;function Oe(e){return typeof e=="string"&&Pe.test(e.trim())?e.trim():void 0}function _e(e){if(typeof e!="string")return;let n=e.trim();return/^(?:https?:\/\/|\/(?!\/)|#|\?)/i.test(n)?n:void 0}function ze(e){if(!Array.isArray(e))return[];let n=[];for(let t of e)t&&typeof t.name=="string"&&A.includes(t.category)&&n.push({name:t.name,category:t.category,cookies:Array.isArray(t.cookies)?t.cookies.filter(r=>typeof r=="string"):void 0});return n}function H(...e){let n=V();for(let t of e){if(!t||typeof t!="object")continue;typeof t.version=="number"&&t.version>=0&&(n.version=Math.floor(t.version)),Le.includes(t.theme)&&(n.theme=t.theme),je.includes(t.position)&&(n.position=t.position);let r=Oe(t.accentColor);r&&(n.accentColor=r);let p=_e(t.privacyPolicyUrl);if(p&&(n.privacyPolicyUrl=p),t.categories&&typeof t.categories=="object")for(let s of A)typeof t.categories[s]=="boolean"&&(n.categories[s]=t.categories[s]);t.services!==void 0&&(n.services=ze(t.services)),t.texts&&typeof t.texts=="object"&&(n.texts=t.texts)}return n}async function ue(e,n,t=3e3){if(typeof fetch!="function")return null;let r=typeof AbortController=="function"?new AbortController:void 0,p=setTimeout(()=>_optionalChain([r, 'optionalAccess', _5 => _5.abort, 'call', _6 => _6()]),t);try{let s=await fetch(`${e.replace(/\/+$/,"")}/api/consent/config?key=${encodeURIComponent(n)}`,{signal:_optionalChain([r, 'optionalAccess', _7 => _7.signal]),credentials:"omit"});if(!s.ok)return null;let l=await s.json();if(!l||typeof l!="object")return null;let C=l.config&&typeof l.config=="object"?l.config:null,g=l.enabled!==!1;return C||!g?{enabled:g,config:C}:null}catch (e4){return null}finally{clearTimeout(p)}}var Me={ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied",functionality_storage:"denied",personalization_storage:"denied",security_storage:"granted",wait_for_update:500},z=e=>e?"granted":"denied";function Q(e){return{analytics_storage:z(e.analytics),ad_storage:z(e.marketing),ad_user_data:z(e.marketing),ad_personalization:z(e.marketing),functionality_storage:z(e.preferences),personalization_storage:z(e.preferences)}}function Ue(e,n){return n==="off"?!1:n==="on"||typeof e.gtag=="function"||Array.isArray(e.dataLayer)}function Be(e){if(typeof e.gtag=="function")return e.gtag;let n=e.dataLayer=e.dataLayer||[],t=function(){n.push(arguments)};return e.gtag=t,t}function ge(e,n){if(!Ue(e,n))return null;let t=Be(e);return{setDefault:()=>t("consent","default",{...Me}),update:r=>t("consent","update",Q(r))}}var ee={pl:{title:"Szanujemy Twoj\u0105 prywatno\u015B\u0107",description:"U\u017Cywamy plik\xF3w cookie, aby strona dzia\u0142a\u0142a poprawnie. Za Twoj\u0105 zgod\u0105 wykorzystujemy je te\u017C do statystyk, personalizacji i reklam. Mo\u017Cesz zaakceptowa\u0107 wszystkie, odrzuci\u0107 wszystkie albo wybra\u0107, na co si\u0119 zgadzasz.",acceptAll:"Akceptuj wszystkie",rejectAll:"Odrzu\u0107 wszystkie",settings:"Ustawienia",save:"Zapisz wyb\xF3r",close:"Zamknij",necessaryTitle:"Niezb\u0119dne",necessaryDescription:"Potrzebne do dzia\u0142ania strony: koszyk, zapami\u0119tanie Twojego wyboru, bezpiecze\u0144stwo. Nie mo\u017Cna ich wy\u0142\u0105czy\u0107.",analyticsTitle:"Statystyki",analyticsDescription:"Pomagaj\u0105 nam zrozumie\u0107, jak odwiedzaj\u0105cy korzystaj\u0105 ze strony, \u017Ceby\u015Bmy mogli j\u0105 ulepsza\u0107.",marketingTitle:"Marketing",marketingDescription:"Pozwalaj\u0105 mierzy\u0107 skuteczno\u015B\u0107 reklam i pokazywa\u0107 Ci oferty dopasowane do zainteresowa\u0144.",preferencesTitle:"Preferencje",preferencesDescription:"Zapami\u0119tuj\u0105 Twoje ustawienia, na przyk\u0142ad j\u0119zyk czy wygl\u0105d strony.",poweredBy:"Powered by"},en:{title:"We value your privacy",description:"We use cookies to make this site work. With your consent we also use them for statistics, personalization and ads. You can accept all, reject all, or choose what you agree to.",acceptAll:"Accept all",rejectAll:"Reject all",settings:"Settings",save:"Save choices",close:"Close",necessaryTitle:"Necessary",necessaryDescription:"Needed for the site to work: the cart, remembering your choice, security. They cannot be turned off.",analyticsTitle:"Analytics",analyticsDescription:"Help us understand how visitors use the site, so we can improve it.",marketingTitle:"Marketing",marketingDescription:"Measure how well ads work and show you offers that match your interests.",preferencesTitle:"Preferences",preferencesDescription:"Remember your settings, such as language or how the site looks.",poweredBy:"Powered by"}},ye={pl:{privacy:"Polityka prywatno\u015Bci",services:"Us\u0142ugi",always:"Zawsze aktywne"},en:{privacy:"Privacy policy",services:"Services",always:"Always on"}};function F(e,n){return e==="pl"||e==="en"?e:/^pl\b/i.test(_nullishCoalesce(n, () => ("")))?"pl":"en"}function X(e,n){let t={...ee[e]},r=_optionalChain([n, 'optionalAccess', _8 => _8[e]]);if(r)for(let p of Object.keys(t)){let s=r[p];typeof s=="string"&&s.trim()!==""&&(t[p]=s)}return t}function De(e){let n=e.replace("#","");n.length===3&&(n=n.replace(/./g,"$&$&"));let t=parseInt(n,16);return[t>>16&255,t>>8&255,t&255]}function me(e){let[n,t,r]=De(e).map(p=>{let s=p/255;return s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4)});return .2126*n+.7152*t+.0722*r}function q(e,n){let[t,r]=[me(e),me(n)].sort((p,s)=>s-p);return(t+.05)/(r+.05)}function Ce(e){return q(e,"#ffffff")>=q(e,"#111111")?"#ffffff":"#111111"}var Y={light:{bg:"#ffffff",fg:"#14171c",muted:"#495260",border:"#c9ced6",off:"#6b7280",thumb:"#ffffff",accent:"#1d4ed8",onAccent:"#ffffff",link:"#1d4ed8"},dark:{bg:"#171a20",fg:"#f1f3f6",muted:"#b7beca",border:"#3a404b",off:"#8b93a1",thumb:"#171a20",accent:"#8ab4ff",onAccent:"#0b1220",link:"#9dc0ff"}},he=e=>`--bg:${e.bg};--fg:${e.fg};--muted:${e.muted};--border:${e.border};--off:${e.off};--thumb:${e.thumb};--accent:${e.accent};--on-accent:${e.onAccent};--link:${e.link};--focus:${e.accent}`,be=`
|
|
2
2
|
:host{all:initial}
|
|
3
3
|
*{box-sizing:border-box}
|
|
4
4
|
[hidden]{display:none!important}
|
|
5
|
-
.root{${
|
|
6
|
-
.root[data-theme=dark]{${
|
|
5
|
+
.root{${he(Y.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}
|
|
6
|
+
.root[data-theme=dark]{${he(Y.dark)};color-scheme:dark}
|
|
7
7
|
button,input{font:inherit;color:inherit}
|
|
8
8
|
.banner,.overlay{pointer-events:auto}
|
|
9
9
|
.banner{position:absolute;background:var(--bg);color:var(--fg);box-shadow:0 8px 32px rgba(0,0,0,.22);max-height:92vh;overflow:auto;outline:none;animation:in .22s ease-out}
|
|
@@ -71,5 +71,5 @@ input:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}
|
|
|
71
71
|
.btn{flex-basis:130px;padding:0 12px}
|
|
72
72
|
}
|
|
73
73
|
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}
|
|
74
|
-
`.replace(/\n/g,"");var Xe='<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect width="16" height="16" rx="4" fill="currentColor" style="color:var(--fg)"/><circle cx="8" cy="8" r="3" fill="var(--bg)"/></svg>',qe='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>',Je="button:not([disabled]),input:not([disabled]),a[href]";function ve(e){let{doc:t,config:n,texts:i,locale:p}=e,s=me[p],l=null,u=null,g,f,y,b,v,h="none",w=null,T=null,E=new Map;function c(o,a={},...d){let m=t.createElement(o);for(let C of Object.keys(a))C==="class"?m.className=a[C]:m.setAttribute(C,a[C]);for(let C of d)m.append(C);return m}function x(o,a,d){let m=c("button",{type:"button",class:o},a);return m.addEventListener("click",d),m}function z(){let o=c("a",{href:`https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(_nullishCoalesce(_optionalChain([t, 'access', _13 => _13.location, 'optionalAccess', _14 => _14.hostname]), () => ("")))}`,target:"_blank",rel:"noopener"});return o.append(i.poweredBy+" "),o.insertAdjacentHTML("beforeend",Xe),o.append(c("b",{},"bitsnap")),c("div",{class:"foot"},o)}function k(){let o=c("p",{class:"desc",id:"d"},i.description);return n.privacyPolicyUrl&&o.append(" ",c("a",{href:n.privacyPolicyUrl,target:"_blank",rel:"noopener"},s.privacy)),o}function j(){v=x("link-btn",i.settings,()=>B()),f=c("div",{class:`banner ${n.position==="bottom"?"bottom":`card ${n.position}`}`,role:"region","aria-live":"polite","aria-labelledby":"t","aria-describedby":"d",tabindex:"-1"},c("div",{class:"inner"},c("div",{class:"text"},c("div",{class:"title",id:"t"},i.title),k()),c("div",{class:"actions"},x("btn",i.acceptAll,e.onAcceptAll),x("btn",i.rejectAll,e.onRejectAll),v),z()))}function U(o){let a=n.services.filter(C=>C.category===o),d=c("input",{type:"checkbox",role:"switch","aria-labelledby":`l-${o}`,"aria-describedby":`p-${o}`});o==="necessary"?(d.checked=!0,d.disabled=!0):E.set(o,d);let m=c("div",{class:"cat"},c("div",{class:"row"},c("span",{class:"cat-title",id:`l-${o}`},i[`${o}Title`]),c("span",{style:"display:flex;align-items:center"},...o==="necessary"?[c("span",{class:"always"},s.always)]:[],c("label",{class:"switch"},d,c("span",{class:"track"})))),c("p",{id:`p-${o}`},i[`${o}Description`]));return a.length>0&&m.append(c("p",{class:"svc"},c("b",{},`${s.services}: `),a.map(C=>C.name).join(", "))),m}function R(){let o=c("button",{type:"button",class:"x","aria-label":i.close});o.insertAdjacentHTML("beforeend",qe),o.addEventListener("click",()=>_());let a=c("div",{class:"d-body"},U("necessary"));for(let d of A)n.categories[d]&&a.append(U(d));b=c("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"st",tabindex:"-1"},c("div",{class:"d-head"},c("div",{class:"title",id:"st"},i.settings),o),a,c("div",{class:"d-foot"},c("div",{class:"actions"},x("btn",i.save,()=>e.onSave(I())),x("btn",i.acceptAll,e.onAcceptAll),x("btn",i.rejectAll,e.onRejectAll)),z())),y=c("div",{class:"overlay"},b),y.addEventListener("mousedown",d=>{d.target===y&&_()})}function I(){let o={analytics:!1,marketing:!1,preferences:!1};return E.forEach((a,d)=>o[d]=a.checked),o}function S(){let o=n.theme==="dark"||n.theme==="auto"&&!!_optionalChain([T, 'optionalAccess', _15 => _15.matches]);g.setAttribute("data-theme",o?"dark":"light"),N(o)}function N(o){let a=n.accentColor;if(a){if(o&&q(a,J.dark.bg)<3){for(let d of["--accent","--focus","--on-accent"])g.style.removeProperty(d);return}g.style.setProperty("--accent",a),g.style.setProperty("--focus",a),g.style.setProperty("--on-accent",he(a))}}function D(){l||(l=c("div",{id:"bitsnap-consent","data-bitsnap-consent-host":""}),u=l.attachShadow({mode:"open"}),u.append(c("style",{},xe)),g=c("div",{class:"root",lang:p}),j(),R(),f.hidden=!0,y.hidden=!0,g.append(f,y),u.append(g),typeof _optionalChain([t, 'access', _16 => _16.defaultView, 'optionalAccess', _17 => _17.matchMedia])=="function"&&(T=t.defaultView.matchMedia("(prefers-color-scheme: dark)"),_optionalChain([T, 'access', _18 => _18.addEventListener, 'optionalCall', _19 => _19("change",S)])),S(),t.body.append(l))}function L(){return Array.from(b.querySelectorAll(Je))}function P(o){if(h!=="settings")return;if(o.key==="Escape"){o.preventDefault(),_();return}if(o.key!=="Tab")return;let a=L();if(a.length===0)return;let d=_optionalChain([u, 'optionalAccess', _20 => _20.activeElement]),m=a[0],C=a[a.length-1],W=!d||!b.contains(d);o.shiftKey&&(W||d===m||d===b)?(o.preventDefault(),C.focus()):!o.shiftKey&&(W||d===C)&&(o.preventDefault(),m.focus())}function K(o=!1){try{D(),h="banner",t.removeEventListener("keydown",P,!0),y.hidden=!0,f.hidden=!1,o&&f.focus({preventScroll:!0})}catch (e11){}}function B(){try{if(D(),h!=="settings"){let a=t.activeElement;w=a&&a!==l&&a!==t.body?a:null}let o=e.getChoices();E.forEach((a,d)=>a.checked=!!_optionalChain([o, 'optionalAccess', _21 => _21[d]])),h="settings",f.hidden=!0,y.hidden=!1,t.addEventListener("keydown",P,!0),b.focus({preventScroll:!0})}catch (e12){}}function _(){h==="settings"&&(t.removeEventListener("keydown",P,!0),y.hidden=!0,e.hasChoice()?(h="none",_optionalChain([w, 'optionalAccess', _22 => _22.focus, 'optionalCall', _23 => _23({preventScroll:!0})])):(h="banner",f.hidden=!1,v.focus({preventScroll:!0})))}function G(){if(!l)return;t.removeEventListener("keydown",P,!0);let o=h==="settings";h="none",f.hidden=!0,y.hidden=!0,o&&_optionalChain([w, 'optionalAccess', _24 => _24.focus, 'optionalCall', _25 => _25({preventScroll:!0})])}function r(){t.removeEventListener("keydown",P,!0),_optionalChain([T, 'optionalAccess', _26 => _26.removeEventListener, 'optionalCall', _27 => _27("change",S)]),_optionalChain([l, 'optionalAccess', _28 => _28.remove, 'call', _29 => _29()]),l=null,u=null,h="none"}return{showBanner:K,showSettings:B,hide:G,destroy:r}}var O=()=>({analytics:!1,marketing:!1,preferences:!1}),we=e=>e&&{id:e.id,ts:e.ts,bv:e.bv,c:{...e.c}};function Y(e={}){let t=typeof window<"u"?window:void 0,n=_optionalChain([t, 'optionalAccess', _30 => _30.document]),i=new Set,p=e.apiHost||se,s=e.collectHost||ae,l=e.projectKey?_chunk3UHPJ6NKjs.b.call(void 0, e.projectKey):null,u=de(_nullishCoalesce(l, () => (void 0)),e.scope),g=!!e.preview,f=$(z()),y=null,b=null,v=null,h=!1,w=!1,T,E=[],c=t&&!g?k(()=>ye(t,e.gcm),null):null;k(()=>_optionalChain([c, 'optionalAccess', _31 => _31.setDefault, 'call', _32 => _32()]),void 0);let x=n&&!g?fe(n,u):null;function z(r){let o={...e.config};return e.theme&&(o.theme=e.theme),e.position&&(o.position=e.position),e.privacyPolicyUrl&&(o.privacyPolicyUrl=e.privacyPolicyUrl),{...r,...o}}function k(r,o){try{return r()}catch (e13){return o}}function j(r){let o=O();for(let a of A)o[a]=!!_optionalChain([r, 'optionalAccess', _33 => _33[a]])&&f.categories[a];return o}function U(r){i.forEach(o=>k(()=>o({...r,c:{...r.c}}),void 0)),k(()=>{_optionalChain([t, 'optionalAccess', _34 => _34.dispatchEvent, 'call', _35 => _35(new t.CustomEvent("bitsnap:consent",{detail:{...r,c:{...r.c}}}))])},void 0)}function R(r,o){g||!l||typeof fetch!="function"||k(()=>{let a=JSON.stringify({k:l,consent_id:o.id,action:r,c:o.c,bv:o.bv,host:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _36 => _36.location, 'optionalAccess', _37 => _37.hostname]), () => ("")),ts:o.ts});fetch(`${s.replace(/\/+$/,"")}/consent`,{method:"POST",keepalive:!0,credentials:"omit",body:a}).catch(()=>{})},void 0)}function I(r){return A.filter(o=>r[o]&&f.categories[o])}function S(r,o){if(!n||w)return;if(g){_optionalChain([v, 'optionalAccess', _38 => _38.hide, 'call', _39 => _39()]);return}let a=_nullishCoalesce(y, () => (b)),d=a?I(a.c).filter(W=>!r[W]):[],m=d.length>0?"withdraw":o,C={id:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _40 => _40.id]), () => (pe())),ts:Math.floor(Date.now()/1e3),bv:f.version,c:r};ue(n,u,C),y=C,b=null,N(C.c),d.length>0&&V(n,f.services,d),_optionalChain([v, 'optionalAccess', _41 => _41.hide, 'call', _42 => _42()]),U({...C,action:m}),R(m,C),d.length>0&&e.reloadOnWithdraw&&D()}function N(r){k(()=>_optionalChain([c, 'optionalAccess', _43 => _43.update, 'call', _44 => _44(r)]),void 0),n&&re(n,r)}function D(){setTimeout(()=>k(()=>_optionalChain([t, 'optionalAccess', _45 => _45.location, 'access', _46 => _46.reload, 'call', _47 => _47()]),void 0),50)}function L(){if(!n||!h||w)return null;if(!v){let r=F(e.locale,_optionalChain([t, 'optionalAccess', _48 => _48.navigator, 'optionalAccess', _49 => _49.language]));v=ve({doc:n,config:f,locale:r,texts:P(X(r,f.texts)),getChoices:()=>_nullishCoalesce(_optionalChain([y, 'optionalAccess', _50 => _50.c]), () => (null)),hasChoice:()=>y!==null,onAcceptAll:()=>S(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all"),onRejectAll:()=>S(O(),"reject_all"),onSave:o=>S(j(o),"custom")})}return v}function P(r){let o=_optionalChain([e, 'access', _51 => _51.title, 'optionalAccess', _52 => _52.trim, 'call', _53 => _53()]),a=_optionalChain([e, 'access', _54 => _54.description, 'optionalAccess', _55 => _55.trim, 'call', _56 => _56()]);return{...r,...o&&{title:o},...a&&{description:a}}}function K(r){_optionalChain([r, 'access', _57 => _57.target, 'optionalAccess', _58 => _58.closest, 'optionalCall', _59 => _59("[data-bitsnap-consent-open]")])&&(r.preventDefault(),G.open())}let B=(async()=>{if(!n||!t)return null;let r=l&&!g?await ce(p,l):null;if(w)return null;let o=_optionalChain([r, 'optionalAccess', _60 => _60.config])?void 0:e.categories;if(f=$(_optionalChain([r, 'optionalAccess', _61 => _61.config]),o?{categories:{...O(),...o}}:void 0,z()),n.readyState==="loading"&&await new Promise(m=>n.addEventListener("DOMContentLoaded",()=>m(),{once:!0})),w)return null;h=!0,n.addEventListener("click",K),T=()=>n.removeEventListener("click",K);let a=!l||_optionalChain([r, 'optionalAccess', _62 => _62.config])!=null,d=_optionalChain([r, 'optionalAccess', _63 => _63.enabled])===!1;return g?_optionalChain([L, 'call', _64 => _64(), 'optionalAccess', _65 => _65.showBanner, 'call', _66 => _66()]):x&&(d||!a||x.bv===f.version)?(y=x,N(j(y.c))):(x&&(b=x),d||_optionalChain([L, 'call', _67 => _67(), 'optionalAccess', _68 => _68.showBanner, 'call', _69 => _69()])),E.splice(0).forEach(m=>k(m,void 0)),k(()=>t.dispatchEvent(new t.CustomEvent("bitsnap:consent:ready")),void 0),we(y)})().catch(()=>null);function _(r){h?r():E.push(r)}let G={get:()=>we(y),denied:r=>_optionalChain([(_nullishCoalesce(y, () => (b))), 'optionalAccess', _70 => _70.c, 'access', _71 => _71[r]])===!1,on(r,o){return r!=="change"||typeof o!="function"?()=>{}:(i.add(o),()=>void i.delete(o))},open(){h?_optionalChain([L, 'call', _72 => _72(), 'optionalAccess', _73 => _73.showSettings, 'call', _74 => _74()]):B.then(()=>_optionalChain([L, 'call', _75 => _75(), 'optionalAccess', _76 => _76.showSettings, 'call', _77 => _77()]))},close(){_optionalChain([v, 'optionalAccess', _78 => _78.hide, 'call', _79 => _79()])},accept:r=>_(()=>S(j(r),"custom")),acceptAll:()=>_(()=>S(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all")),rejectAll:()=>_(()=>S(O(),"reject_all")),reset(){if(!n||w)return;if(g){_optionalChain([L, 'call', _80 => _80(), 'optionalAccess', _81 => _81.showBanner, 'call', _82 => _82()]);return}let r=_nullishCoalesce(y, () => (b)),o=r?I(r.c):[];ge(n,u),y=null,b=r,k(()=>_optionalChain([c, 'optionalAccess', _83 => _83.update, 'call', _84 => _84(O())]),void 0),o.length>0&&V(n,f.services,o),U({id:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _85 => _85.id]), () => ("")),ts:Math.floor(Date.now()/1e3),bv:f.version,c:O(),action:"reset"}),r&&o.length>0&&R("withdraw",{id:r.id,ts:Math.floor(Date.now()/1e3),bv:f.version,c:O()}),_optionalChain([L, 'call', _86 => _86(), 'optionalAccess', _87 => _87.showBanner, 'call', _88 => _88(!0)]),o.length>0&&e.reloadOnWithdraw&&D()},ready:B,destroy(){w=!0,_optionalChain([T, 'optionalCall', _89 => _89()]),_optionalChain([v, 'optionalAccess', _90 => _90.destroy, 'call', _91 => _91()]),v=null,i.clear()}};return Ye(G)}function Ye(e){let t={...e};for(let n of Object.keys(e)){let i=e[n];typeof i=="function"&&(t[n]=(...p)=>{try{return i(...p)}catch (e14){return n==="get"?null:n==="on"?()=>{}:void 0}})}return t}function Ve(e){let{projectKey:t,theme:n,locale:i,position:p,privacyPolicyUrl:s,scope:l,apiHost:u,collectHost:g,reloadOnWithdraw:f,gcm:y,preview:b,title:v,description:h}=e,w=JSON.stringify(_nullishCoalesce(e.config, () => (null))),T=_react.useRef.call(void 0, e.config);T.current=e.config;let E=JSON.stringify(_nullishCoalesce(e.categories, () => (null))),c=_react.useRef.call(void 0, e.categories);return c.current=e.categories,_chunk3UHPJ6NKjs.h.call(void 0, ()=>{if(window.BitsnapConsent)return;let x=Y({projectKey:t,theme:n,locale:i,position:p,privacyPolicyUrl:s,scope:l,apiHost:u,collectHost:g,reloadOnWithdraw:f,gcm:y,preview:b,title:v,description:h,categories:c.current,config:T.current});return window.BitsnapConsent=x,()=>{x.destroy(),window.BitsnapConsent===x&&delete window.BitsnapConsent}},[t,n,i,p,s,l,u,g,f,y,b,v,h,E,w]),null}var Te="null",Se=null;function Qe(){let e=typeof window>"u"?null:_nullishCoalesce(_optionalChain([window, 'access', _92 => _92.BitsnapConsent, 'optionalAccess', _93 => _93.get, 'call', _94 => _94()]), () => (null)),t=JSON.stringify(e);return t!==Te&&(Te=t,Se=e),Se}function et(e){return window.addEventListener("bitsnap:consent",e),window.addEventListener("bitsnap:consent:ready",e),()=>{window.removeEventListener("bitsnap:consent",e),window.removeEventListener("bitsnap:consent:ready",e)}}function tt(){let e=_react.useSyncExternalStore.call(void 0, et,Qe,()=>null),t=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _95 => _95.BitsnapConsent, 'optionalAccess', _96 => _96.open, 'call', _97 => _97()]),[]),n=_react.useCallback.call(void 0, l=>_optionalChain([window, 'access', _98 => _98.BitsnapConsent, 'optionalAccess', _99 => _99.accept, 'call', _100 => _100(l)]),[]),i=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _101 => _101.BitsnapConsent, 'optionalAccess', _102 => _102.acceptAll, 'call', _103 => _103()]),[]),p=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _104 => _104.BitsnapConsent, 'optionalAccess', _105 => _105.rejectAll, 'call', _106 => _106()]),[]),s=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _107 => _107.BitsnapConsent, 'optionalAccess', _108 => _108.reset, 'call', _109 => _109()]),[]);return{consent:e,decided:e!==null,open:t,accept:n,acceptAll:i,rejectAll:p,reset:s}}exports.BitsnapConsent = Ve; exports.DEFAULT_TEXTS = ee; exports.createConsent = Y; exports.defaultConfig = Z; exports.mergeConfig = $; exports.mergeTexts = X; exports.resolveLocale = F; exports.toConsentModeUpdate = Q; exports.useConsent = tt;
|
|
74
|
+
`.replace(/\n/g,"");var He='<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect width="16" height="16" rx="4" fill="currentColor" style="color:var(--fg)"/><circle cx="8" cy="8" r="3" fill="var(--bg)"/></svg>',Re='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>',Ie="button:not([disabled]),input:not([disabled]),a[href]";function ve(e){let{doc:n,config:t,texts:r,locale:p}=e,s=ye[p],l=null,C=null,g,u,f,b,x,h="none",w=null,T=null,S=new Map;function c(o,a={},...d){let y=n.createElement(o);for(let m of Object.keys(a))m==="class"?y.className=a[m]:y.setAttribute(m,a[m]);for(let m of d)y.append(m);return y}function v(o,a,d){let y=c("button",{type:"button",class:o},a);return y.addEventListener("click",d),y}function M(){let o=c("a",{href:`https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(_nullishCoalesce(_optionalChain([n, 'access', _9 => _9.location, 'optionalAccess', _10 => _10.hostname]), () => ("")))}`,target:"_blank",rel:"noopener"});return o.append(r.poweredBy+" "),o.insertAdjacentHTML("beforeend",He),o.append(c("b",{},"bitsnap")),c("div",{class:"foot"},o)}function k(){let o=c("p",{class:"desc",id:"d"},r.description);return t.privacyPolicyUrl&&o.append(" ",c("a",{href:t.privacyPolicyUrl,target:"_blank",rel:"noopener"},s.privacy)),o}function j(){x=v("link-btn",r.settings,()=>D()),u=c("div",{class:`banner ${t.position==="bottom"?"bottom":`card ${t.position}`}`,role:"region","aria-live":"polite","aria-labelledby":"t","aria-describedby":"d",tabindex:"-1"},c("div",{class:"inner"},c("div",{class:"text"},c("div",{class:"title",id:"t"},r.title),k()),c("div",{class:"actions"},v("btn",r.acceptAll,e.onAcceptAll),v("btn",r.rejectAll,e.onRejectAll),x),M()))}function U(o){let a=t.services.filter(m=>m.category===o),d=c("input",{type:"checkbox",role:"switch","aria-labelledby":`l-${o}`,"aria-describedby":`p-${o}`});o==="necessary"?(d.checked=!0,d.disabled=!0):S.set(o,d);let y=c("div",{class:"cat"},c("div",{class:"row"},c("span",{class:"cat-title",id:`l-${o}`},r[`${o}Title`]),c("span",{style:"display:flex;align-items:center"},...o==="necessary"?[c("span",{class:"always"},s.always)]:[],c("label",{class:"switch"},d,c("span",{class:"track"})))),c("p",{id:`p-${o}`},r[`${o}Description`]));return a.length>0&&y.append(c("p",{class:"svc"},c("b",{},`${s.services}: `),a.map(m=>m.name).join(", "))),y}function I(){let o=c("button",{type:"button",class:"x","aria-label":r.close});o.insertAdjacentHTML("beforeend",Re),o.addEventListener("click",()=>O());let a=c("div",{class:"d-body"},U("necessary"));for(let d of A)t.categories[d]&&a.append(U(d));b=c("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"st",tabindex:"-1"},c("div",{class:"d-head"},c("div",{class:"title",id:"st"},r.settings),o),a,c("div",{class:"d-foot"},c("div",{class:"actions"},v("btn",r.save,()=>e.onSave(N())),v("btn",r.acceptAll,e.onAcceptAll),v("btn",r.rejectAll,e.onRejectAll)),M())),f=c("div",{class:"overlay"},b),f.addEventListener("mousedown",d=>{d.target===f&&O()})}function N(){let o={analytics:!1,marketing:!1,preferences:!1};return S.forEach((a,d)=>o[d]=a.checked),o}function E(){let o=t.theme==="dark"||t.theme==="auto"&&!!_optionalChain([T, 'optionalAccess', _11 => _11.matches]);g.setAttribute("data-theme",o?"dark":"light"),$(o)}function $(o){let a=t.accentColor;if(a){if(o&&q(a,Y.dark.bg)<3){for(let d of["--accent","--focus","--on-accent"])g.style.removeProperty(d);return}g.style.setProperty("--accent",a),g.style.setProperty("--focus",a),g.style.setProperty("--on-accent",Ce(a))}}function B(){l||(l=c("div",{id:"bitsnap-consent","data-bitsnap-consent-host":""}),C=l.attachShadow({mode:"open"}),C.append(c("style",{},be)),g=c("div",{class:"root",lang:p}),j(),I(),u.hidden=!0,f.hidden=!0,g.append(u,f),C.append(g),typeof _optionalChain([n, 'access', _12 => _12.defaultView, 'optionalAccess', _13 => _13.matchMedia])=="function"&&(T=n.defaultView.matchMedia("(prefers-color-scheme: dark)"),_optionalChain([T, 'access', _14 => _14.addEventListener, 'optionalCall', _15 => _15("change",E)])),E(),n.body.append(l))}function L(){return Array.from(b.querySelectorAll(Ie))}function P(o){if(h!=="settings")return;if(o.key==="Escape"){o.preventDefault(),O();return}if(o.key!=="Tab")return;let a=L();if(a.length===0)return;let d=_optionalChain([C, 'optionalAccess', _16 => _16.activeElement]),y=a[0],m=a[a.length-1],W=!d||!b.contains(d);o.shiftKey&&(W||d===y||d===b)?(o.preventDefault(),m.focus()):!o.shiftKey&&(W||d===m)&&(o.preventDefault(),y.focus())}function K(o=!1){try{B(),h="banner",n.removeEventListener("keydown",P,!0),f.hidden=!0,u.hidden=!1,o&&u.focus({preventScroll:!0})}catch (e5){}}function D(){try{if(B(),h!=="settings"){let a=n.activeElement;w=a&&a!==l&&a!==n.body?a:null}let o=e.getChoices();S.forEach((a,d)=>a.checked=!!_optionalChain([o, 'optionalAccess', _17 => _17[d]])),h="settings",u.hidden=!0,f.hidden=!1,n.addEventListener("keydown",P,!0),b.focus({preventScroll:!0})}catch (e6){}}function O(){h==="settings"&&(n.removeEventListener("keydown",P,!0),f.hidden=!0,e.hasChoice()?(h="none",_optionalChain([w, 'optionalAccess', _18 => _18.focus, 'optionalCall', _19 => _19({preventScroll:!0})])):(h="banner",u.hidden=!1,x.focus({preventScroll:!0})))}function G(){if(!l)return;n.removeEventListener("keydown",P,!0);let o=h==="settings";h="none",u.hidden=!0,f.hidden=!0,o&&_optionalChain([w, 'optionalAccess', _20 => _20.focus, 'optionalCall', _21 => _21({preventScroll:!0})])}function i(){n.removeEventListener("keydown",P,!0),_optionalChain([T, 'optionalAccess', _22 => _22.removeEventListener, 'optionalCall', _23 => _23("change",E)]),_optionalChain([l, 'optionalAccess', _24 => _24.remove, 'call', _25 => _25()]),l=null,C=null,h="none"}return{showBanner:K,showSettings:D,hide:G,destroy:i}}var _=()=>({analytics:!1,marketing:!1,preferences:!1}),xe=e=>e&&{id:e.id,ts:e.ts,bv:e.bv,c:{...e.c}};function Z(e={}){let n=typeof window<"u"?window:void 0,t=_optionalChain([n, 'optionalAccess', _26 => _26.document]),r=new Set,p=e.apiHost||pe,s=e.collectHost||fe,l=e.projectKey?_chunkXIHGWNTSjs.b.call(void 0, e.projectKey):null,C=_chunkXIHGWNTSjs.i.call(void 0, _nullishCoalesce(l, () => (void 0)),e.scope),g=!!e.preview,u=H(M()),f=null,b=null,x=null,h=!1,w=!1,T,S=[],c=n&&!g?k(()=>ge(n,e.gcm),null):null;k(()=>_optionalChain([c, 'optionalAccess', _27 => _27.setDefault, 'call', _28 => _28()]),void 0);let v=t&&!g?_chunkXIHGWNTSjs.k.call(void 0, t,C):null;function M(i){let o={...e.config};return e.theme&&(o.theme=e.theme),e.position&&(o.position=e.position),e.privacyPolicyUrl&&(o.privacyPolicyUrl=e.privacyPolicyUrl),{...i,...o}}function k(i,o){try{return i()}catch (e7){return o}}function j(i){let o=_();for(let a of A)o[a]=!!_optionalChain([i, 'optionalAccess', _29 => _29[a]])&&u.categories[a];return o}function U(i){r.forEach(o=>k(()=>o({...i,c:{...i.c}}),void 0)),k(()=>{_optionalChain([n, 'optionalAccess', _30 => _30.dispatchEvent, 'call', _31 => _31(new n.CustomEvent("bitsnap:consent",{detail:{...i,c:{...i.c}}}))])},void 0)}function I(i,o){g||!l||typeof fetch!="function"||k(()=>{let a=JSON.stringify({k:l,consent_id:o.id,action:i,c:o.c,bv:o.bv,host:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _32 => _32.location, 'optionalAccess', _33 => _33.hostname]), () => ("")),ts:o.ts});fetch(`${s.replace(/\/+$/,"")}/consent`,{method:"POST",keepalive:!0,credentials:"omit",body:a}).catch(()=>{})},void 0)}function N(i){return A.filter(o=>i[o]&&u.categories[o])}function E(i,o){if(!t||w)return;if(g){_optionalChain([x, 'optionalAccess', _34 => _34.hide, 'call', _35 => _35()]);return}let a=_nullishCoalesce(f, () => (b)),d=a?N(a.c).filter(W=>!i[W]):[],y=d.length>0?"withdraw":o,m={id:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _36 => _36.id]), () => (_chunkXIHGWNTSjs.j.call(void 0, ))),ts:Math.floor(Date.now()/1e3),bv:u.version,c:i};_chunkXIHGWNTSjs.l.call(void 0, t,C,m),f=m,b=null,$(m.c),d.length>0&&_chunkXIHGWNTSjs.o.call(void 0, t,u.services,d),_optionalChain([x, 'optionalAccess', _37 => _37.hide, 'call', _38 => _38()]),U({...m,action:y}),I(y,m),d.length>0&&e.reloadOnWithdraw&&B()}function $(i){k(()=>_optionalChain([c, 'optionalAccess', _39 => _39.update, 'call', _40 => _40(i)]),void 0),t&&de(t,i)}function B(){setTimeout(()=>k(()=>_optionalChain([n, 'optionalAccess', _41 => _41.location, 'access', _42 => _42.reload, 'call', _43 => _43()]),void 0),50)}function L(){if(!t||!h||w)return null;if(!x){let i=F(e.locale,_optionalChain([n, 'optionalAccess', _44 => _44.navigator, 'optionalAccess', _45 => _45.language]));x=ve({doc:t,config:u,locale:i,texts:P(X(i,u.texts)),getChoices:()=>_nullishCoalesce(_optionalChain([f, 'optionalAccess', _46 => _46.c]), () => (null)),hasChoice:()=>f!==null,onAcceptAll:()=>E(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all"),onRejectAll:()=>E(_(),"reject_all"),onSave:o=>E(j(o),"custom")})}return x}function P(i){let o=_optionalChain([e, 'access', _47 => _47.title, 'optionalAccess', _48 => _48.trim, 'call', _49 => _49()]),a=_optionalChain([e, 'access', _50 => _50.description, 'optionalAccess', _51 => _51.trim, 'call', _52 => _52()]);return{...i,...o&&{title:o},...a&&{description:a}}}function K(i){_optionalChain([i, 'access', _53 => _53.target, 'optionalAccess', _54 => _54.closest, 'optionalCall', _55 => _55("[data-bitsnap-consent-open]")])&&(i.preventDefault(),G.open())}let D=(async()=>{if(!t||!n)return null;let i=l&&!g?await ue(p,l):null;if(w)return null;let o=_optionalChain([i, 'optionalAccess', _56 => _56.config])?void 0:e.categories;if(u=H(_optionalChain([i, 'optionalAccess', _57 => _57.config]),o?{categories:{..._(),...o}}:void 0,M()),t.readyState==="loading"&&await new Promise(y=>t.addEventListener("DOMContentLoaded",()=>y(),{once:!0})),w)return null;h=!0,t.addEventListener("click",K),T=()=>t.removeEventListener("click",K);let a=!l||_optionalChain([i, 'optionalAccess', _58 => _58.config])!=null,d=_optionalChain([i, 'optionalAccess', _59 => _59.enabled])===!1;return g?_optionalChain([L, 'call', _60 => _60(), 'optionalAccess', _61 => _61.showBanner, 'call', _62 => _62()]):v&&(d||!a||v.bv===u.version)?(f=v,$(j(f.c))):(v&&(b=v),d||_optionalChain([L, 'call', _63 => _63(), 'optionalAccess', _64 => _64.showBanner, 'call', _65 => _65()])),S.splice(0).forEach(y=>k(y,void 0)),k(()=>n.dispatchEvent(new n.CustomEvent("bitsnap:consent:ready")),void 0),xe(f)})().catch(()=>null);function O(i){h?i():S.push(i)}let G={scope:e.scope==="project"&&l?"project":"global",projectKey:l,get:()=>xe(f),denied:i=>_optionalChain([(_nullishCoalesce(f, () => (b))), 'optionalAccess', _66 => _66.c, 'access', _67 => _67[i]])===!1,on(i,o){return i!=="change"||typeof o!="function"?()=>{}:(r.add(o),()=>void r.delete(o))},open(){h?_optionalChain([L, 'call', _68 => _68(), 'optionalAccess', _69 => _69.showSettings, 'call', _70 => _70()]):D.then(()=>_optionalChain([L, 'call', _71 => _71(), 'optionalAccess', _72 => _72.showSettings, 'call', _73 => _73()]))},close(){_optionalChain([x, 'optionalAccess', _74 => _74.hide, 'call', _75 => _75()])},accept:i=>O(()=>E(j(i),"custom")),acceptAll:()=>O(()=>E(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all")),rejectAll:()=>O(()=>E(_(),"reject_all")),reset(){if(!t||w)return;if(g){_optionalChain([L, 'call', _76 => _76(), 'optionalAccess', _77 => _77.showBanner, 'call', _78 => _78()]);return}let i=_nullishCoalesce(f, () => (b)),o=i?N(i.c):[];_chunkXIHGWNTSjs.m.call(void 0, t,C),f=null,b=i,k(()=>_optionalChain([c, 'optionalAccess', _79 => _79.update, 'call', _80 => _80(_())]),void 0),o.length>0&&_chunkXIHGWNTSjs.o.call(void 0, t,u.services,o),U({id:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _81 => _81.id]), () => ("")),ts:Math.floor(Date.now()/1e3),bv:u.version,c:_(),action:"reset"}),i&&o.length>0&&I("withdraw",{id:i.id,ts:Math.floor(Date.now()/1e3),bv:u.version,c:_()}),_optionalChain([L, 'call', _82 => _82(), 'optionalAccess', _83 => _83.showBanner, 'call', _84 => _84(!0)]),o.length>0&&e.reloadOnWithdraw&&B()},ready:D,destroy(){w=!0,_optionalChain([T, 'optionalCall', _85 => _85()]),_optionalChain([x, 'optionalAccess', _86 => _86.destroy, 'call', _87 => _87()]),x=null,r.clear()}};return Ne(G)}function Ne(e){let n={...e};for(let t of Object.keys(e)){let r=e[t];typeof r=="function"&&(n[t]=(...p)=>{try{return r(...p)}catch (e8){return t==="get"?null:t==="on"?()=>{}:void 0}})}return n}function Ke(e){let{projectKey:n,theme:t,locale:r,position:p,privacyPolicyUrl:s,scope:l,apiHost:C,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:b,title:x,description:h}=e,w=JSON.stringify(_nullishCoalesce(e.config, () => (null))),T=_react.useRef.call(void 0, e.config);T.current=e.config;let S=JSON.stringify(_nullishCoalesce(e.categories, () => (null))),c=_react.useRef.call(void 0, e.categories);return c.current=e.categories,_chunkXIHGWNTSjs.p.call(void 0, ()=>{if(window.BitsnapConsent)return;let v=Z({projectKey:n,theme:t,locale:r,position:p,privacyPolicyUrl:s,scope:l,apiHost:C,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:b,title:x,description:h,categories:c.current,config:T.current});return window.BitsnapConsent=v,()=>{v.destroy(),window.BitsnapConsent===v&&delete window.BitsnapConsent}},[n,t,r,p,s,l,C,g,u,f,b,x,h,S,w]),null}var ke="null",Te=null;function Ge(){let e=typeof window>"u"?null:_nullishCoalesce(_optionalChain([window, 'access', _88 => _88.BitsnapConsent, 'optionalAccess', _89 => _89.get, 'call', _90 => _90()]), () => (null)),n=JSON.stringify(e);return n!==ke&&(ke=n,Te=e),Te}function We(e){return window.addEventListener("bitsnap:consent",e),window.addEventListener("bitsnap:consent:ready",e),()=>{window.removeEventListener("bitsnap:consent",e),window.removeEventListener("bitsnap:consent:ready",e)}}function Fe(){let e=_react.useSyncExternalStore.call(void 0, We,Ge,()=>null),n=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _91 => _91.BitsnapConsent, 'optionalAccess', _92 => _92.open, 'call', _93 => _93()]),[]),t=_react.useCallback.call(void 0, l=>_optionalChain([window, 'access', _94 => _94.BitsnapConsent, 'optionalAccess', _95 => _95.accept, 'call', _96 => _96(l)]),[]),r=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _97 => _97.BitsnapConsent, 'optionalAccess', _98 => _98.acceptAll, 'call', _99 => _99()]),[]),p=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _100 => _100.BitsnapConsent, 'optionalAccess', _101 => _101.rejectAll, 'call', _102 => _102()]),[]),s=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _103 => _103.BitsnapConsent, 'optionalAccess', _104 => _104.reset, 'call', _105 => _105()]),[]);return{consent:e,decided:e!==null,open:n,accept:t,acceptAll:r,rejectAll:p,reset:s}}exports.BitsnapConsent = Ke; exports.DEFAULT_TEXTS = ee; exports.createConsent = Z; exports.defaultConfig = V; exports.mergeConfig = H; exports.mergeTexts = X; exports.resolveLocale = F; exports.toConsentModeUpdate = Q; exports.useConsent = Fe;
|
|
75
75
|
//# sourceMappingURL=consent.js.map
|
package/dist/consent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAAgD,+BAA4B,8BCAlB,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BD,CAAAA,CAAO,gBAAA,CAAiB,MAAA,CAAQ,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAAA,CAC/DD,CAAAA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O,IAAA,CACxC,IAAMC,CAAAA,CAAa,OAAO,eAAA,EAAoB,UAAA,CAAa,IAAI,eAAA,CAAoB,KAAA,CAAA,CAC7EC,CAAAA,CAAQ,UAAA,CAAW,CAAA,CAAA,kBAAMD,CAAAA,6BAAY,KAAA,mBAAM,GAAA,CAAGD,CAAS,CAAA,CAC7D,GAAI,CACF,IAAMG,CAAAA,CAAW,MAAM,KAAA,CACrB,CAAA,EAAA;ACvFgB;AAAA;AAAA;AAIK,MAAA;AACgB,uBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACgK3B","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n.banner{position:absolute;background:var(--bg);color:var(--fg);box-shadow:0 8px 32px rgba(0,0,0,.22);max-height:92vh;overflow:auto;outline:none;animation:in .22s ease-out}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);padding:16px 24px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{display:grid;grid-template-columns:1fr auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 32px;align-items:center;max-width:1200px;margin:0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{font-size:16px;font-weight:650;line-height:1.35;margin:0 0 4px}\n.desc{margin:0;color:var(--muted)}\n.desc a,.link-btn{color:var(--link)}\n.btn{min-height:44px;padding:0 20px;border:2px solid var(--accent);border-radius:10px;background:var(--accent);color:var(--on-accent);font-weight:600;cursor:pointer;flex:1 1 150px;white-space:nowrap}\n.btn:hover{filter:brightness(.94)}\n.link-btn{min-height:44px;padding:0 12px;border:0;background:none;font-weight:500;text-decoration:underline;text-underline-offset:3px;cursor:pointer}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:4px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px;animation:fade .2s ease-out}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none;animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{grid-template-columns:1fr;grid-template-areas:\"text\" \"actions\" \"foot\";gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px;padding:0 12px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n banner.hidden = false;\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n banner.hidden = true;\n overlay.hidden = false;\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n banner.hidden = false;\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n banner.hidden = true;\n overlay.hidden = true;\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAA+F,+BAA4B,8BCAjE,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BD,CAAAA,CAAO,gBAAA,CAAiB,MAAA,CAAQ,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAAA,CAC/DD,CAAAA,CAAO,gBAAA,CAAiB,OAAA,CAAS,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAClE,CAAC,CACH,CAGA,SAASC,EAAAA,CAAIC,CAAAA,CAAeC,CAAAA,CAA2D,CACrF,IAAMJ,CAAAA,CAASG,CAAAA,CAAI,aAAA,CAAc,QAAQ,CAAA,CACzC,GAAA,CAAA,GAAW,CAAE,IAAA,CAAAE,CAAAA,CAAM,KAAA,CAAAC,CAAM,CAAA,GAAK,KAAA,CAAM,IAAA,CAAKF,CAAAA,CAAY,UAAU,CAAA,CACzDC,CAAAA,GAAS,MAAA,EAAUA,CAAAA,GAAS,qBAAA,EAAA,CAC5BA,CAAAA,GAA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACqKV","file":"/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n /**\n * Whose choice this banner holds: `project` keeps one cookie per project key\n * (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.\n */\n readonly scope: \"global\" | \"project\";\n /** The bare public project key the banner was started with, if any (`pk_` stripped). */\n readonly projectKey: string | null;\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n.banner{position:absolute;background:var(--bg);color:var(--fg);box-shadow:0 8px 32px rgba(0,0,0,.22);max-height:92vh;overflow:auto;outline:none;animation:in .22s ease-out}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);padding:16px 24px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{display:grid;grid-template-columns:1fr auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 32px;align-items:center;max-width:1200px;margin:0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{font-size:16px;font-weight:650;line-height:1.35;margin:0 0 4px}\n.desc{margin:0;color:var(--muted)}\n.desc a,.link-btn{color:var(--link)}\n.btn{min-height:44px;padding:0 20px;border:2px solid var(--accent);border-radius:10px;background:var(--accent);color:var(--on-accent);font-weight:600;cursor:pointer;flex:1 1 150px;white-space:nowrap}\n.btn:hover{filter:brightness(.94)}\n.link-btn{min-height:44px;padding:0 12px;border:0;background:none;font-weight:500;text-decoration:underline;text-underline-offset:3px;cursor:pointer}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:4px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px;animation:fade .2s ease-out}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none;animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{grid-template-columns:1fr;grid-template-areas:\"text\" \"actions\" \"foot\";gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px;padding:0 12px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n banner.hidden = false;\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n banner.hidden = true;\n overlay.hidden = false;\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n banner.hidden = false;\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n banner.hidden = true;\n overlay.hidden = true;\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}
|