{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "lemlist", "type": "registry:item", "title": "Lemlist", "description": "Seven independent Lemlist raw resource streams with acknowledged activity intervals and complete replayable reads.", "dependencies": [ "@chkit/core@^0.2.0-beta.12", "@chkit/plugin-ingest@^0.2.0-beta.12", "zod@^4.3.6" ], "devDependencies": [ "@types/bun@^1.2.0" ], "files": [ { "path": "lemlist/README.md", "type": "registry:file", "target": "src/integrations/lemlist/README.md", "content": "# Lemlist raw ingestion\n\nSync seven Lemlist resources into independent raw ClickHouse tables. Readers pass provider records without field transformations; campaign/contact joins and reporting belong in ClickHouse. The `raw` column uses ClickHouse native JSON, not an exact copy of the response text: storage normalization can omit explicit null properties and empty objects. See the [native JSON storage fidelity contract](https://chkit.obsessiondb.com/api-sync/destinations/).\n\nSet `LEMLIST_API_KEY` in the runtime environment, or set `apiKey` in `config.ts`, and configure a direct ClickHouse connection. Edit `config.ts` for the account namespace, page size, initial date, overlap, and interval length. Configuration and the key are checked when a stream runs, so schema commands do not need them; invalid settings or a missing key fail each stream before any request. Native JSON requires ClickHouse 25.3 or later.\n\n`pipeline.ts` groups seven independently selectable streams in one account pipeline. Each resource owns its checkpoint and discovery; execution order is not a dependency. `sources/` contains the resource readers; `client.ts` parses the configuration and owns authenticated Lemlist requests, `paginate()` traversal, and payload validation. `index.ts` exports the pipeline and raw schema. Use `createLemlistPipeline(config)` to bind reader settings, including `apiKey`, for another account. Page size must be between 1 and 100. The exported raw tables use the installation's `lemlistConfig.database` at schema discovery; factories do not change storage names.\n\nKeep each stream ID and destination tied to one Lemlist account. The reader does not resolve the authenticated account identity: when changing the key to another account, use new stream IDs and destinations before ingesting so previous watermarks cannot skip that account's history.\n\n```sh\nbunx chkit check\nbunx chkit generate --name add_lemlist\n# Review the migration before applying it.\nbunx chkit migrate --apply\nbunx chkit ingest run --tag provider:lemlist\n```\n\n## Resources\n\n- `activities` → `lemlist_activities_raw`\n- `campaigns` → `lemlist_campaigns_raw`\n- `contacts` → `lemlist_contacts_raw`\n- `companies` → `lemlist_companies_raw`\n- `campaign_leads` → `lemlist_campaign_leads_raw`\n- `inbox_conversations` → `lemlist_inbox_conversations_raw`\n- `inbox_messages` → `lemlist_inbox_messages_raw`\n\nContacts represent team-wide people; campaign leads are their distinct campaign-specific records and memberships. The [contact list](https://developer.lemlist.com/api-reference/endpoints/contacts/get-many-contacts) is a reduced representation, so the contacts reader fetches full same-resource records in batches of at most 100 IDs. Native custom fields and `campaigns[].campaignId/leadId` references remain intact. Companies are read through their complete paginated list.\n\nCampaign leads discover every campaign themselves and use [the JSON export](https://developer.lemlist.com/api-reference/endpoints/campaigns/export-campaign-leads-v2) with `state=all`. The ordinary campaign lead list documents a 500-record limit and no continuation; it is not used. Export records are preserved under `raw.data`, with `source_id` and `campaign_id` alongside them. Exports do not guarantee `contactId`; join the native lead ID against contacts' campaign references in ClickHouse rather than matching email addresses.\n\nConversations independently discover all current team member IDs through `GET /team?version=v2`, then paginate each user's inbox. Set `inboxUserIds` to an explicit nonempty list to restrict this stream. An empty or omitted list means all discovered team members. A missing member list fails visibly; it is not an empty successful inbox. Conversation envelopes contain `source_id`, `user_id`, and provider fields under `data`, subject to native JSON normalization.\n\nMessages independently paginate all current contacts, including old contacts, then page each contact's complete accessible message history with `skip/limit`. `inboxUserIds` scopes only conversations; messages cover all accessible contacts in the account. Every message request explicitly sets `markAsRead=false`. Readers issue only GET requests and do not mark conversations read or perform inbox actions. Message envelopes contain `source_id`, `contact_id`, and provider fields under `data`, subject to native JSON normalization.\n\n## Sync and recovery\n\nActivities use the provider's inclusive `minDate`/`maxDate` filters on `createdAt`. The initial range starts at `2000-01-01`; later runs replay one day before the last committed watermark. A large range is split into intervals of at most thirty days. Offset pagination stays local to each interval; an unfinished interval always starts at offset zero after failure. The checkpoint advances only after every page of an interval has been written successfully, including empty intervals. An explicit backfill resumes completed intervals in its own checkpoint namespace while retaining one day of overlap.\n\nThe upper bound does not freeze the provider dataset. Late arrivals or deletions can still change offset pages, and older activities can receive backfilled metadata. Do not treat activity offsets as change cursors or row chunks as immutable page identities. Periodic historical replay refreshes metadata and catches arrivals beyond the overlap:\n\n```sh\nbunx chkit ingest run --tag provider:lemlist --tag resource:activities --backfill reconcile-2026-10-04 --from 2000-01-01\nbunx chkit ingest status --tag provider:lemlist --json\n```\n\nUse a new backfill ID for each complete reconciliation; reusing an ID resumes that backfill. A reused ID with an upper bound earlier than its committed frontier is rejected; use a new ID for a narrower historical range. Date intervals intentionally have inclusive shared boundaries; stable `_id` row keys reconcile repeated observations. Empty completion markers carry interval identities, while mutable row chunks do not.\n\nThe six resources besides activities use `fullSync()`: their list/export endpoints do not document reliable modification filters. Each successful execution, including empty results, is recorded in its own journal namespace. An interrupted stream repeats its own complete discovery and pagination from the beginning. Campaigns use `createdAt:asc` ordering; campaign leads revisit every campaign, and messages revisit every contact. Creation timestamps and inbox page numbers are not change tokens. These full reads ignore date backfill bounds and do not provide date-range backfills.\n\nOffset and inbox pagination validate response shapes, bounds, advertised totals, and repeated pages; malformed or incomplete results fail before successful completion. Full reads are live lists rather than provider snapshots, so ongoing source changes can require another replay. Lead exports arrive as one JSON array per campaign and are yielded in bounded chunks; a large export still requires memory for the provider's complete response. API-key rate limits are handled by executor retries; pipeline defaults serialize streams and requests.\n\nRaw observations do not infer deletions. Removed contacts, companies, campaign leads, conversations, messages, campaigns, or activities remain stored; full sync does not automatically delete missing IDs. Content and availability remain limited to the API key's accessible records. Run one ingestion process per ClickHouse target at a time.\n\n## Identities and upgrading\n\nVersion 0.2.0 adds five raw destinations to the two original tables. Generate and review additive migrations before running the new streams. Existing activities/campaigns stream IDs, timestamp state, raw fields and native `_id` row keys stay unchanged; those original tables belong to one installation/account.\n\nContacts and companies store provider fields under `raw.data` with `source_id`, subject to native JSON normalization; their row IDs encode `[sourceId, providerId]`. Campaign lead, conversation, and message row IDs encode `[sourceId, parentId, providerId]`. Conversation parent IDs are user IDs, preserving distinct user inbox observations even when the native conversation ID matches. Provider IDs remain unchanged inside `raw.data`. Changing the account requires new stream namespaces and destinations; changing the conversation user scope should use a new source namespace or explicitly reconcile its prior observations.\n\n## Fixture tests\n\n```sh\nbunx chkit add lemlist --with-tests\nbun test src/integrations/lemlist/tests/basic.test.ts\n```\n\nThe portable suites check all seven resources alone and in reverse order, complete contact hydration, exports beyond 500 leads, user/contact pagination, unread preservation, empty completion, malformed continuations, source/destination replay, account configuration, and existing activity interval/backfill recovery without live credentials.\n\n```sh\nbun test src/integrations/lemlist/tests\n```\n" }, { "path": "lemlist/index.ts", "type": "registry:file", "target": "src/integrations/lemlist/index.ts", "content": "export { createLemlistPipeline, lemlistPipeline } from './pipeline.js'\nexport { lemlist_activitiesRaw } from './sources/activities.js'\nexport { lemlist_campaignsRaw } from './sources/campaigns.js'\nexport { lemlist_contactsRaw } from './sources/contacts.js'\nexport { lemlist_companiesRaw } from './sources/companies.js'\nexport { lemlist_campaignLeadsRaw } from './sources/campaign-leads.js'\nexport { lemlist_inboxConversationsRaw } from './sources/inbox-conversations.js'\nexport { lemlist_inboxMessagesRaw } from './sources/inbox-messages.js'\n" }, { "path": "lemlist/config.ts", "type": "registry:file", "target": "src/integrations/lemlist/config.ts", "content": "import { z } from 'zod'\n\nconst name = z.string().refine((value) => value.trim() !== '', 'must not be blank')\nconst missingKey = 'Set LEMLIST_API_KEY or pass apiKey.'\nconst apiKey = z.string().optional().pipe(z.string({ error: missingKey }).trim().min(1, missingKey))\n\nconst lemlistConfigSchema = z.object({\n /** Stable checkpoint namespace for one account; use a new value when switching accounts. */\n sourceId: name,\n database: name,\n pageSize: z.int().min(1).max(100),\n start: z.date(),\n overlapMs: z.number().nonnegative(),\n intervalMs: z.int().positive(),\n /** Empty or omitted discovers all team members for the conversations stream. */\n inboxUserIds: z.array(name).readonly()\n .refine((ids) => new Set(ids).size === ids.length, 'must not repeat a user ID').optional(),\n /** Lemlist API key; read when a stream runs, never by schema commands. */\n apiKey,\n})\n\nexport type LemlistConfig = z.input\n\nexport const lemlistReaderConfigSchema = lemlistConfigSchema.omit({ database: true })\nexport type LemlistReaderConfig = z.input\n\n// Storage is configured here before schema discovery.\nexport const lemlistConfig: LemlistConfig = {\n sourceId: 'lemlist',\n database: 'default',\n pageSize: 100,\n start: new Date('2000-01-01T00:00:00Z'),\n overlapMs: 24 * 60 * 60 * 1000,\n intervalMs: 30 * 24 * 60 * 60 * 1000,\n inboxUserIds: [],\n apiKey: process.env.LEMLIST_API_KEY,\n}\n" }, { "path": "lemlist/client.ts", "type": "registry:file", "target": "src/integrations/lemlist/client.ts", "content": "import { paginate, type Page, type SourceContext, type TimestampRange } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { lemlistReaderConfigSchema, type LemlistReaderConfig } from './config.js'\n\nexport type ListResource = 'activities' | 'campaigns' | 'contacts' | 'companies'\nexport type InboxScope = { userId: string } | { contactId: string }\nexport type LemlistItem = z.infer\nexport type LemlistSettings = Omit, 'apiKey'>\nexport interface InboxCursor { page: number; skip: number }\n\nexport interface LemlistClient {\n settings: LemlistSettings\n list(resource: ListResource, window?: TimestampRange): AsyncGenerator>\n inbox(scope: InboxScope): AsyncGenerator>\n contacts(ids: readonly string[]): Promise\n campaignLeads(campaignId: string): Promise\n teamUserIds(): Promise\n}\n\ntype Get = (path: string, params: Record) => Promise\n\nconst nonNegative = z.int().nonnegative()\nconst lemlistId = z.string().refine((value) => value.trim() !== '', 'must not be blank')\nconst lemlistItem = z.looseObject({ _id: lemlistId })\nconst lemlistItems = z.array(lemlistItem)\n .refine((items) => new Set(items.map((item) => item._id)).size === items.length, 'must not repeat an object ID')\n// The public API returns arrays; retain compatibility with older campaign envelopes.\nconst campaignItems = z.union([lemlistItems, z.looseObject({ campaigns: lemlistItems }).transform(({ campaigns }) => campaigns)])\nconst offsetListing = z.looseObject({ data: lemlistItems, limit: z.int().positive(), total: nonNegative, offset: nonNegative })\nconst inboxListing = z.looseObject({\n data: lemlistItems,\n pagination: z.looseObject({ totalItems: nonNegative, perPage: z.int().positive(), currentPage: z.int().positive(), totalPages: nonNegative, nextPage: z.int().nullable() }),\n})\nconst team = z.looseObject({ userIds: z.array(lemlistId).optional(), users: z.array(z.looseObject({ userId: lemlistId })).optional() })\n\nexport function createLemlistClient(context: SourceContext, config: LemlistReaderConfig): LemlistClient {\n const { apiKey, ...settings } = lemlistReaderConfigSchema.parse(config)\n const authorization = `Basic ${Buffer.from(`:${apiKey}`).toString('base64')}`\n const get: Get = async (path, params) => {\n const url = new URL(`https://api.lemlist.com/api${path}`)\n for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value)\n const response = await context.fetch(url, { headers: { Authorization: authorization }, redirect: 'error' })\n return response.json()\n }\n return {\n settings,\n list: (resource, window) => listPages(context, get, settings.pageSize, resource, window),\n inbox: (scope) => inboxPages(context, get, settings.pageSize, scope),\n contacts: async (ids) => {\n const items = lemlistItems.parse(await get('/contacts', { idsOrEmails: ids.join(',') }))\n const expected = new Set(ids)\n if (items.length !== ids.length || items.some((item) => !expected.has(item._id))) {\n throw new Error('Lemlist contact lookup did not return every discovered contact; replay this stream.')\n }\n return items\n },\n // The normal lead list has a 500-row cap and no continuation. This endpoint explicitly exports all states.\n campaignLeads: async (campaignId) => lemlistItems.parse(\n await get(`/v2/campaigns/${encodeURIComponent(campaignId)}/export/leads`, { state: 'all', format: 'json' }),\n ),\n teamUserIds: async () => {\n const members = team.parse(await get('/team', { version: 'v2' }))\n const ids = members.userIds ?? members.users?.map((user) => user.userId)\n if (!ids?.length) throw new Error('Lemlist team has no member IDs; configure inboxUserIds or restore team access.')\n return [...new Set(ids)]\n },\n }\n}\n\n/** Offsets are local traversal positions, never durable change cursors. */\nfunction listPages(context: SourceContext, get: Get, pageSize: number, resource: ListResource, window: TimestampRange | undefined) {\n const seen = new Set()\n return paginate({\n context, initial: 0, label: `GET /${resource}`,\n fetchPage: async (offset = 0) => {\n const params: Record = { limit: String(pageSize), offset: String(offset) }\n if (resource === 'activities' || resource === 'campaigns') params.version = 'v2'\n if (window) {\n params.minDate = window.from.toISOString()\n params.maxDate = window.to.toISOString()\n } else if (resource !== 'contacts') {\n params.sortBy = 'createdAt'\n params.sortOrder = 'asc'\n }\n const result = await get(`/${resource}`, params)\n let items: LemlistItem[]\n let next: number | undefined\n if (resource === 'contacts' || resource === 'companies') {\n const listing = offsetListing.parse(result)\n items = listing.data\n if (listing.offset !== offset || listing.limit > pageSize || items.length > listing.limit ||\n offset + items.length > listing.total || (items.length < listing.limit && offset + items.length < listing.total)) {\n throw new Error(`Lemlist ${resource} has inconsistent pagination; replay this stream.`)\n }\n next = offset + items.length < listing.total ? offset + listing.limit : undefined\n } else {\n items = resource === 'campaigns' ? campaignItems.parse(result) : lemlistItems.parse(result)\n if (items.length > pageSize) throw new Error(`Lemlist ${resource} exceeds pageSize.`)\n next = items.length === pageSize ? offset + items.length : undefined\n }\n rejectRepeatedPage(items, seen, resource)\n if (next !== undefined && !Number.isSafeInteger(next)) throw new Error('Lemlist offset exceeded the safe integer range.')\n return { items, next }\n },\n })\n}\n\n/** Inbox pagination is page-based; the messages endpoint accepts the equivalent skip. */\nfunction inboxPages(context: SourceContext, get: Get, pageSize: number, scope: InboxScope) {\n const path = 'userId' in scope ? '/inbox' : `/inbox/${encodeURIComponent(scope.contactId)}`\n const seen = new Set()\n let expectedTotal: number | undefined\n let received = 0\n return paginate({\n context, initial: { page: 1, skip: 0 }, label: `GET ${path}`,\n fetchPage: async (cursor: InboxCursor = { page: 1, skip: 0 }) => {\n const params: Record = { limit: String(pageSize) }\n if ('userId' in scope) {\n params.userId = scope.userId\n params.page = String(cursor.page)\n } else {\n params.skip = String(cursor.skip)\n params.markAsRead = 'false'\n }\n const { data: items, pagination } = inboxListing.parse(await get(path, params))\n const { totalItems: total, perPage, currentPage, totalPages, nextPage } = pagination\n if (currentPage !== cursor.page || perPage > pageSize || items.length > perPage ||\n (expectedTotal !== undefined && total !== expectedTotal) ||\n (nextPage !== null && (nextPage !== currentPage + 1 || items.length === 0 || currentPage >= totalPages)) ||\n (nextPage === null && totalPages > currentPage)) {\n throw new Error('Lemlist inbox has malformed or incomplete pagination; replay this stream.')\n }\n rejectRepeatedPage(items, seen, path)\n const count = received + items.length\n if (count > total || (nextPage === null && count !== total)) throw new Error('Lemlist inbox ended before its advertised complete collection.')\n expectedTotal = total\n received = count\n const next = nextPage === null ? undefined : { page: nextPage, skip: cursor.skip + perPage }\n return { items, next }\n },\n })\n}\n\nfunction rejectRepeatedPage(items: readonly LemlistItem[], seen: Set, label: string) {\n if (items.some((item) => seen.has(item._id))) throw new Error(`Lemlist ${label} repeated a page or object ID; replay this stream.`)\n for (const item of items) seen.add(item._id)\n}\n" }, { "path": "lemlist/pipeline.ts", "type": "registry:file", "target": "src/integrations/lemlist/pipeline.ts", "content": "import { definePipeline, defineStream, fullSync } from '@chkit/plugin-ingest'\n\nimport { lemlistConfig, type LemlistReaderConfig } from './config.js'\nimport { createActivityWindow, lemlist_activitiesRaw, readActivities } from './sources/activities.js'\nimport { lemlist_campaignsRaw, readCampaigns } from './sources/campaigns.js'\nimport { lemlist_contactsRaw, readContacts } from './sources/contacts.js'\nimport { lemlist_companiesRaw, readCompanies } from './sources/companies.js'\nimport { lemlist_campaignLeadsRaw, readCampaignLeads } from './sources/campaign-leads.js'\nimport { lemlist_inboxConversationsRaw, readInboxConversations } from './sources/inbox-conversations.js'\nimport { lemlist_inboxMessagesRaw, readInboxMessages } from './sources/inbox-messages.js'\n\n/** One account pipeline; every resource owns its discovery and checkpoint. */\nexport function createLemlistPipeline(config: LemlistReaderConfig = lemlistConfig) {\n const boundConfig = { ...config, start: new Date(config.start), inboxUserIds: config.inboxUserIds ? [...config.inboxUserIds] : undefined }\n return definePipeline({\n id: boundConfig.sourceId, tags: ['provider:lemlist'], maxStreams: 1, maxFetches: 1,\n streams: [\n defineStream({\n id: `${boundConfig.sourceId}.activities`, tags: ['resource:activities'], destination: lemlist_activitiesRaw,\n incremental: createActivityWindow(boundConfig), batchSize: 500,\n read: (context) => readActivities(context, boundConfig),\n }),\n defineStream({\n id: `${boundConfig.sourceId}.campaigns`, tags: ['resource:campaigns'], destination: lemlist_campaignsRaw,\n incremental: fullSync(),\n read: (context) => readCampaigns(context, boundConfig),\n }),\n defineStream({ id: `${boundConfig.sourceId}.contacts`, tags: ['resource:contacts'], destination: lemlist_contactsRaw,\n incremental: fullSync(), read: (context) => readContacts(context, boundConfig) }),\n defineStream({ id: `${boundConfig.sourceId}.companies`, tags: ['resource:companies'], destination: lemlist_companiesRaw,\n incremental: fullSync(), read: (context) => readCompanies(context, boundConfig) }),\n defineStream({ id: `${boundConfig.sourceId}.campaign_leads`, tags: ['resource:campaign_leads'], destination: lemlist_campaignLeadsRaw,\n incremental: fullSync(), read: (context) => readCampaignLeads(context, boundConfig) }),\n defineStream({ id: `${boundConfig.sourceId}.inbox_conversations`, tags: ['resource:inbox_conversations'], destination: lemlist_inboxConversationsRaw,\n incremental: fullSync(), read: (context) => readInboxConversations(context, boundConfig) }),\n defineStream({ id: `${boundConfig.sourceId}.inbox_messages`, tags: ['resource:inbox_messages'], destination: lemlist_inboxMessagesRaw,\n incremental: fullSync(), read: (context) => readInboxMessages(context, boundConfig) }),\n ],\n })\n}\n\nexport const lemlistPipeline = createLemlistPipeline()\n" }, { "path": "lemlist/sources/activities.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/activities.ts", "content": "import { rawRows, rawTable, timestampWindow, type IncrementalStrategy, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_activitiesRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_activities_raw' })\n\nexport async function* readActivities(context: ReadContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n for (let from = context.selection.from; from < context.selection.to;) {\n const to = new Date(Math.min(from.getTime() + client.settings.intervalMs, context.selection.to.getTime()))\n for await (const page of client.list('activities', { from, to })) {\n yield { rows: rawRows(page.items, (item) => item._id) }\n }\n // Only an exhausted interval is a safe frontier. Its mutable offsets restart at zero.\n const watermark = new Date(Math.max(to.getTime(), Date.parse(context.state?.watermark ?? to.toISOString()))).toISOString()\n yield { rows: [], state: { watermark }, id: `completed-interval:${from.toISOString()}/${to.toISOString()}` }\n from = to\n }\n}\n\nexport function createActivityWindow(config: LemlistReaderConfig): IncrementalStrategy {\n const window = timestampWindow({ start: config.start, overlapMs: config.overlapMs })\n return {\n ...window,\n plan(input: Parameters[0]) {\n const selection = window.plan(input)\n if (input.range && input.state) {\n const frontier = Date.parse(input.state.watermark)\n if (selection.to.getTime() < frontier) {\n throw new Error('Lemlist backfill upper bound precedes its committed interval frontier; use a new backfill ID for a narrower historical range.')\n }\n return { ...selection, from: new Date(Math.max(selection.from.getTime(), frontier - config.overlapMs)) }\n }\n return selection\n },\n }\n}\n" }, { "path": "lemlist/sources/campaigns.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/campaigns.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_campaignsRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_campaigns_raw' })\n\n// No reliable modification filter: default fullSync records completion and safely replays failures.\nexport async function* readCampaigns(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n for await (const page of client.list('campaigns')) {\n yield { rows: rawRows(page.items, (item) => item._id) }\n }\n}\n" }, { "path": "lemlist/tests/basic.test.ts", "type": "registry:file", "target": "src/integrations/lemlist/tests/basic.test.ts", "role": "test", "content": "import { expect, test } from 'bun:test'\nimport { runIngestion, selectStreams, type PipelineDefinition } from '@chkit/plugin-ingest'\nimport { createMemoryDestination, createMemoryJournal } from '@chkit/plugin-ingest/testing'\n\nimport { lemlistConfig } from '../config.js'\nimport { createLemlistPipeline } from '../index.js'\n\nconst fixtureConfig = { ...lemlistConfig, apiKey: 'fixture' }\nconst cutoff = new Date('2000-03-01T00:00:00Z')\nconst retry = { retries: 0 }\n\ntest('Lemlist commits only exhausted date intervals and replays the unfinished interval with overlap', async () => {\n let fail = true\n const journal = createMemoryJournal()\n let acknowledgeInterval = () => {}\n const intervalCommitted = new Promise((resolve) => { acknowledgeInterval = resolve })\n const append = journal.append\n journal.append = async (events) => {\n await append(events)\n if (events.some((event) => JSON.stringify(event.checkpoint?.state) === '{\"watermark\":\"2000-01-31T00:00:00.000Z\"}')) acknowledgeInterval()\n }\n const windows: { from: string | null; to: string | null; offset: string | null }[] = []\n const env = lemlistEnv(async (url) => {\n const from = url.searchParams.get('minDate')\n windows.push({ from, to: url.searchParams.get('maxDate'), offset: url.searchParams.get('offset') })\n if (fail && from !== '2000-01-01T00:00:00.000Z') {\n await intervalCommitted\n return new Response('denied', { status: 403 })\n }\n return Response.json([{ _id: from, custom: { retained: true } }])\n })\n const destination = createMemoryDestination()\n const request = { selected: selected(), backfill: undefined }\n expect((await runIngestion(request, { ...env, journal, destination, now: () => cutoff, retry })).ok).toBe(false)\n expect((await journal.readCheckpoint('lemlist.activities')).envelope?.state).toEqual({ watermark: '2000-01-31T00:00:00.000Z' })\n expect(destination.tables.get('default.lemlist_activities_raw')?.[0]?.raw).toMatchObject({ custom: { retained: true } })\n fail = false\n expect((await runIngestion(request, { ...env, journal, destination, now: () => cutoff, retry })).ok).toBe(true)\n expect(windows[2]).toEqual({ from: '2000-01-30T00:00:00.000Z', to: '2000-02-29T00:00:00.000Z', offset: '0' })\n expect((await journal.readCheckpoint('lemlist.activities')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n})\n\ntest('Lemlist resumes isolated explicit backfills from the completed interval frontier', async () => {\n let fail = true\n const starts: string[] = []\n const env = lemlistEnv(async (url) => {\n const from = url.searchParams.get('minDate') ?? ''\n starts.push(from)\n if (fail && from !== '2025-01-01T00:00:00.000Z') return new Response('denied', { status: 403 })\n return Response.json([])\n })\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const request = { selected: selected(), backfill: { id: 'history', from: new Date('2025-01-01T00:00:00Z'), to: new Date('2025-03-01T00:00:00Z') } }\n expect((await runIngestion(request, { ...env, journal, destination, now: () => new Date('2026-01-01'), retry })).ok).toBe(false)\n expect((await journal.readCheckpoint('lemlist.activities#backfill:history')).envelope?.state).toEqual({ watermark: '2025-01-31T00:00:00.000Z' })\n fail = false\n expect((await runIngestion(request, { ...env, journal, destination, now: () => new Date('2026-01-01'), retry })).ok).toBe(true)\n expect(starts[2]).toBe('2025-01-30T00:00:00.000Z')\n expect((await journal.readCheckpoint('lemlist.activities')).envelope).toBeUndefined()\n})\n\ntest('Lemlist rejects a narrowed completed backfill upper bound without regressing its frontier', async () => {\n let requests = 0\n const env = lemlistEnv(async () => { requests++; return Response.json([]) })\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const backfill = { id: 'narrowed', from: new Date('2025-01-01T00:00:00Z'), to: new Date('2025-03-01T00:00:00Z') }\n const request = { selected: selected(), backfill }\n expect((await runIngestion(request, { ...env, journal, destination, now: () => new Date('2026-01-01'), retry })).ok).toBe(true)\n const completedRequests = requests\n // This upper bound is still after the overlap's lower bound, but must not move the watermark backwards.\n const result = await runIngestion({ ...request, backfill: { ...backfill, to: new Date('2025-02-28T12:00:00Z') } }, {\n ...env, journal, destination, now: () => new Date('2026-01-01'), retry,\n })\n expect(result.ok).toBe(false)\n expect(result.streams[0]?.error).toContain('use a new backfill ID')\n expect(requests).toBe(completedRequests)\n expect((await journal.readCheckpoint('lemlist.activities#backfill:narrowed')).envelope?.state).toEqual({ watermark: '2025-03-01T00:00:00.000Z' })\n})\n\ntest('Lemlist paginates a whole date interval and a rejected sink cannot advance it', async () => {\n const offsets: string[] = []\n const env = lemlistEnv(async (url) => {\n offsets.push(url.searchParams.get('offset') ?? '')\n expect(url.searchParams.get('minDate')).toBe('2000-01-01T00:00:00.000Z')\n expect(url.searchParams.get('maxDate')).toBe('2000-01-02T00:00:00.000Z')\n return Response.json(url.searchParams.get('offset') === '0' ? Array.from({ length: 100 }, (_, index) => ({ _id: String(index) })) : [{ _id: 'last' }])\n })\n const journal = createMemoryJournal()\n const request = { selected: selected(), backfill: undefined }\n const result = await runIngestion(request, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now: () => new Date('2000-01-02'), retry })\n expect(result.ok).toBe(false)\n expect((await journal.readCheckpoint('lemlist.activities')).envelope).toBeUndefined()\n expect(offsets).toEqual(['0', '100'])\n})\n\ntest('Lemlist empty activity intervals commit and campaigns always scan from zero', async () => {\n const paths: URL[] = []\n const env = lemlistEnv(async (url) => { paths.push(url); return Response.json({ campaigns: [] }) })\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const request = { selected: selected('campaigns'), backfill: undefined }\n expect((await runIngestion(request, { ...env, journal, destination, now: () => cutoff, retry })).ok).toBe(true)\n expect((await runIngestion(request, { ...env, journal, destination, now: () => new Date('2000-03-02'), retry })).ok).toBe(true)\n expect(paths.map((url) => url.searchParams.get('offset'))).toEqual(['0', '0'])\n expect(paths.every((url) => url.searchParams.get('sortBy') === 'createdAt' && url.searchParams.get('sortOrder') === 'asc')).toBe(true)\n expect((await journal.readCheckpoint('lemlist.campaigns')).lastSuccessSeq).toBeGreaterThan(0)\n expect(journal.events.filter((event) => event.namespaceId === 'lemlist.campaigns' && event.eventKind === 'work_finished' && event.workState === 'succeeded')).toHaveLength(2)\n const empty = lemlistEnv(async () => Response.json([]))\n expect((await runIngestion({ selected: selected(), backfill: undefined }, { ...empty, journal, destination, now: () => cutoff, retry })).ok).toBe(true)\n expect((await journal.readCheckpoint('lemlist.activities')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n})\n\ntest('Lemlist binds account configuration and its API key to independent resource streams and preserves activity progress after a campaign failure', async () => {\n const config = { ...fixtureConfig, sourceId: 'lemlist.sales', pageSize: 2, start: new Date('2026-01-01'), overlapMs: 0, intervalMs: 24 * 60 * 60 * 1000, apiKey: 'sales-key' }\n const urls: URL[] = []\n let campaignsAvailable = false\n const env = lemlistEnv((url, init) => {\n urls.push(url)\n expect(init?.headers).toEqual({ Authorization: `Basic ${Buffer.from(':sales-key').toString('base64')}` })\n if (url.pathname.endsWith('/campaigns')) return campaignsAvailable ? Response.json({ campaigns: [] }) : new Response('denied', { status: 403 })\n return Response.json(url.searchParams.get('offset') === '0' ? [{ _id: 'a' }, { _id: 'b' }] : [{ _id: 'c', custom: true }])\n })\n const pipeline = createLemlistPipeline(config)\n config.pageSize = 100\n config.start.setUTCFullYear(2000)\n config.apiKey = 'changed'\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const selected = selectStreams([pipeline], []).filter((item) => ['lemlist.sales.activities', 'lemlist.sales.campaigns'].includes(item.stream.id))\n const result = await runIngestion({ selected, backfill: undefined }, { ...env, journal, destination, now: () => new Date('2026-01-02'), retry })\n expect(result.streams.map((stream) => [stream.streamId, stream.outcome])).toEqual([\n ['lemlist.sales.activities', 'succeeded'], ['lemlist.sales.campaigns', 'failed'],\n ])\n expect((await journal.readCheckpoint('lemlist.sales.activities')).envelope?.state).toEqual({ watermark: '2026-01-02T00:00:00.000Z' })\n expect((await journal.readCheckpoint('lemlist.sales.campaigns')).lastSuccessSeq).toBe(0)\n expect(urls.filter((url) => url.pathname.endsWith('/activities')).map((url) => [url.searchParams.get('minDate'), url.searchParams.get('offset'), url.searchParams.get('limit')])).toEqual([\n ['2026-01-01T00:00:00.000Z', '0', '2'], ['2026-01-01T00:00:00.000Z', '2', '2'],\n ])\n expect(destination.tables.get('default.lemlist_activities_raw')?.map((row) => row.id)).toEqual(['a', 'b', 'c'])\n campaignsAvailable = true\n urls.length = 0\n expect((await runIngestion({ selected: selectStreams([pipeline], ['resource:campaigns']), backfill: undefined }, { ...env, journal, destination })).ok).toBe(true)\n expect(urls.map((url) => url.pathname)).toEqual(['/api/campaigns'])\n expect((await journal.readCheckpoint('lemlist.sales.campaigns')).lastSuccessSeq).toBeGreaterThan(0)\n expect((await journal.readCheckpoint('lemlist.activities')).envelope).toBeUndefined()\n})\n\ntest('Lemlist rejects repeated offset payloads without recording full-scan completion', async () => {\n const offsets: string[] = []\n const env = lemlistEnv((url) => {\n offsets.push(url.searchParams.get('offset') ?? '')\n return Response.json({ campaigns: [{ _id: 'repeated' }] })\n })\n const pipeline = createLemlistPipeline({ ...fixtureConfig, pageSize: 1 })\n const journal = createMemoryJournal()\n const result = await runIngestion({ selected: selectStreams([pipeline], ['resource:campaigns']), backfill: undefined }, { ...env, journal, destination: createMemoryDestination() })\n expect(result.ok).toBe(false)\n expect(result.streams[0]?.error).toContain('repeated a page')\n expect(offsets).toEqual(['0', '1'])\n expect((await journal.readCheckpoint('lemlist.campaigns')).lastSuccessSeq).toBe(0)\n})\n\ntest('Lemlist full-sync campaigns publish changed observations on the next run', async () => {\n let title = 'before'\n const env = lemlistEnv(() => Response.json({ campaigns: [{ _id: 'campaign', title }] }))\n const pipeline = createLemlistPipeline(fixtureConfig)\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const request = { selected: selectStreams([pipeline], ['resource:campaigns']), backfill: undefined }\n expect((await runIngestion(request, { ...env, journal, destination })).ok).toBe(true)\n title = 'after'\n expect((await runIngestion(request, { ...env, journal, destination })).ok).toBe(true)\n expect(destination.tables.get('default.lemlist_campaigns_raw')?.map((row) => row.raw)).toEqual([\n { _id: 'campaign', title: 'before' }, { _id: 'campaign', title: 'after' },\n ])\n})\n\nfunction selected(resource = 'activities', pipeline: PipelineDefinition = createLemlistPipeline(fixtureConfig)) {\n return selectStreams([pipeline], [`resource:${resource}`])\n}\n\nfunction lemlistEnv(handler: (url: URL, init: RequestInit | undefined) => Response | Promise) {\n return { fetch: async (input: string | URL, init?: RequestInit) => handler(new URL(input), init) }\n}\n" }, { "path": "lemlist/sources/contacts.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/contacts.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_contactsRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_contacts_raw' })\n\nexport async function* readContacts(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n const { sourceId } = client.settings\n for await (const page of client.list('contacts')) {\n if (page.items.length === 0) continue\n // List items omit custom fields; hydrate complete objects of the same resource in <=100-ID batches.\n const contacts = await client.contacts(page.items.map((item) => item._id))\n yield { rows: rawRows(contacts.map((data) => ({ source_id: sourceId, data })), ({ data }) => JSON.stringify([sourceId, data._id])) }\n }\n}\n" }, { "path": "lemlist/sources/companies.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/companies.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_companiesRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_companies_raw' })\n\nexport async function* readCompanies(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n const { sourceId } = client.settings\n for await (const page of client.list('companies')) {\n yield { rows: rawRows(page.items.map((data) => ({ source_id: sourceId, data })), ({ data }) => JSON.stringify([sourceId, data._id])) }\n }\n}\n" }, { "path": "lemlist/sources/campaign-leads.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/campaign-leads.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_campaignLeadsRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_campaign_leads_raw' })\n\nexport async function* readCampaignLeads(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n const { sourceId, pageSize } = client.settings\n // Own complete campaign discovery: old campaigns can gain leads without changing their creation date.\n for await (const campaigns of client.list('campaigns')) {\n for (const campaign of campaigns.items) {\n const leads = await client.campaignLeads(campaign._id)\n for (let offset = 0; offset < leads.length; offset += pageSize) {\n const rows = leads.slice(offset, offset + pageSize).map((data) => ({ source_id: sourceId, campaign_id: campaign._id, data }))\n yield { rows: rawRows(rows, ({ data }) => JSON.stringify([sourceId, campaign._id, data._id])) }\n }\n }\n }\n}\n" }, { "path": "lemlist/sources/inbox-conversations.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/inbox-conversations.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_inboxConversationsRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_inbox_conversations_raw' })\n\nexport async function* readInboxConversations(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n const { sourceId, inboxUserIds } = client.settings\n const userIds = inboxUserIds?.length ? inboxUserIds : await client.teamUserIds()\n for (const userId of userIds) {\n for await (const page of client.inbox({ userId })) {\n yield { rows: rawRows(page.items.map((data) => ({ source_id: sourceId, user_id: userId, data })), ({ data }) => JSON.stringify([sourceId, userId, data._id])) }\n }\n }\n}\n" }, { "path": "lemlist/sources/inbox-messages.ts", "type": "registry:file", "target": "src/integrations/lemlist/sources/inbox-messages.ts", "content": "import { rawRows, rawTable, type SourceContext } from '@chkit/plugin-ingest'\n\nimport { createLemlistClient } from '../client.js'\nimport { lemlistConfig, type LemlistReaderConfig } from '../config.js'\n\nexport const lemlist_inboxMessagesRaw = rawTable({ database: lemlistConfig.database, name: 'lemlist_inbox_messages_raw' })\n\nexport async function* readInboxMessages(context: SourceContext, config: LemlistReaderConfig) {\n const client = createLemlistClient(context, config)\n const { sourceId } = client.settings\n // Discover all current contacts independently; recent parent/activity watermarks cannot cover late replies.\n for await (const contacts of client.list('contacts')) {\n for (const contact of contacts.items) {\n for await (const page of client.inbox({ contactId: contact._id })) {\n yield { rows: rawRows(page.items.map((data) => ({ source_id: sourceId, contact_id: contact._id, data })), ({ data }) => JSON.stringify([sourceId, contact._id, data._id])) }\n }\n }\n }\n}\n" }, { "path": "lemlist/tests/resources.test.ts", "type": "registry:file", "target": "src/integrations/lemlist/tests/resources.test.ts", "role": "test", "content": "import { expect, test } from 'bun:test'\nimport { runIngestion, selectStreams, type PipelineDefinition } from '@chkit/plugin-ingest'\nimport { createMemoryDestination, createMemoryJournal } from '@chkit/plugin-ingest/testing'\n\nimport { lemlistConfig } from '../config.js'\nimport { createLemlistPipeline } from '../index.js'\n\nconst resources = ['activities', 'campaigns', 'contacts', 'companies', 'campaign_leads', 'inbox_conversations', 'inbox_messages']\nconst now = () => new Date('2026-01-02T00:00:00Z')\nconst retry = { retries: 0 }\nconst fixtureConfig = { ...lemlistConfig, sourceId: 'lemlist.fixture', start: new Date('2026-01-01'), apiKey: 'fixture' }\n\nfunction pipeline(options: { pageSize?: number; inboxUserIds?: readonly string[] } = {}) {\n return createLemlistPipeline({ ...fixtureConfig, ...options })\n}\n\nfunction lemlistFetch(handler: (url: URL, init: RequestInit | undefined) => Response | Promise = fixture) {\n return async (input: string | URL, init?: RequestInit) => handler(new URL(input), init)\n}\n\nfunction selected(value: PipelineDefinition, resource?: string) {\n return selectStreams([value], resource ? [`resource:${resource}`] : [])\n}\n\nfunction listing(data: { _id: string; [key: string]: unknown }[], url: URL, total = data.length) {\n return Response.json({ data, total, limit: Number(url.searchParams.get('limit')), offset: Number(url.searchParams.get('offset')) })\n}\n\nfunction inbox(data: { _id: string; [key: string]: unknown }[], options: { page?: number; next?: number | null; total?: number; limit?: number } = {}) {\n return Response.json({ data, pagination: {\n totalItems: options.total ?? data.length, currentPage: options.page ?? 1, nextPage: options.next ?? null,\n previousPage: null, perPage: options.limit ?? 100, totalPages: options.next ? options.next : options.page ?? (data.length ? 1 : 0),\n } })\n}\n\nfunction fixture(url: URL): Response {\n switch (url.pathname) {\n case '/api/activities': return Response.json([{ _id: 'act', type: 'emailsSent', createdAt: '2026-01-01T12:00:00Z' }])\n case '/api/campaigns': return Response.json([{ _id: 'cam', createdAt: '2000-01-01', name: 'Outreach' }])\n case '/api/contacts': return url.searchParams.has('idsOrEmails') ? Response.json([{\n _id: 'ctc', companyId: 'cpn', fields: { custom: 'kept' }, unsubscribed: false,\n campaigns: [{ campaignId: 'cam', leadId: 'lea', leadState: 'review' }],\n }]) : listing([{ _id: 'ctc' }], url)\n case '/api/companies': return listing([{ _id: 'cpn', fields: { name: 'Company', custom: { kept: true } } }], url)\n case '/api/v2/campaigns/cam/export/leads': return Response.json([{ _id: 'lea', email: 'person@example.com', lastState: 'emailsReplied', custom: 'kept' }])\n case '/api/team': return Response.json({ _id: 'tea', userIds: ['usr'] })\n case '/api/inbox': return inbox([{ _id: 'ibx', contactId: 'ctc', users: [{ userId: 'usr', read: false }], channels: ['email'] }])\n case '/api/inbox/ctc': return inbox([{ _id: 'message', type: 'emailsReplied', contactId: 'ctc', leadId: 'lea', campaignId: 'cam', message: '

Reply

' }])\n default: throw new Error(`Unexpected fixture request: ${url.pathname}`)\n }\n}\n\ntest('Lemlist has seven independently selectable resources with raw provider IDs and joins', async () => {\n const paths: string[] = []\n const fetch = lemlistFetch((url, init) => {\n expect(init?.method ?? 'GET').toBe('GET')\n paths.push(url.pathname)\n return fixture(url)\n })\n const value = pipeline()\n expect(value.streams.map((stream) => stream.id)).toEqual(resources.map((resource) => `lemlist.fixture.${resource}`))\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n expect((await runIngestion({ selected: selected(value).reverse(), backfill: undefined }, { fetch, journal, destination, now, retry })).ok).toBe(true)\n expect(paths.filter((path) => path === '/api/contacts')).toHaveLength(3)\n expect(destination.tables.get('default.lemlist_contacts_raw')?.[0]).toMatchObject({\n id: '[\"lemlist.fixture\",\"ctc\"]', raw: { source_id: 'lemlist.fixture', data: { companyId: 'cpn', fields: { custom: 'kept' }, campaigns: [{ campaignId: 'cam', leadId: 'lea' }] } },\n })\n expect(destination.tables.get('default.lemlist_campaign_leads_raw')?.[0]).toMatchObject({\n id: '[\"lemlist.fixture\",\"cam\",\"lea\"]', raw: { source_id: 'lemlist.fixture', campaign_id: 'cam', data: { _id: 'lea', lastState: 'emailsReplied', custom: 'kept' } },\n })\n expect(destination.tables.get('default.lemlist_inbox_messages_raw')?.[0]).toMatchObject({\n id: '[\"lemlist.fixture\",\"ctc\",\"message\"]', raw: { source_id: 'lemlist.fixture', contact_id: 'ctc', data: { message: '

Reply

', leadId: 'lea' } },\n })\n for (const resource of resources) expect((await journal.readCheckpoint(`lemlist.fixture.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n})\n\nfor (const resource of resources) {\n test(`Lemlist ${resource} discovers its own scope when selected alone`, async () => {\n const fetch = lemlistFetch()\n const value = pipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion({ selected: selected(value, resource), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })).ok).toBe(true)\n expect(journal.events.filter((event) => event.namespaceId.startsWith('lemlist.fixture.'))\n .every((event) => event.namespaceId === `lemlist.fixture.${resource}`)).toBe(true)\n })\n}\n\ntest('Lemlist exports more than 500 campaign leads without calling the capped list endpoint', async () => {\n const paths: URL[] = []\n const fetch = lemlistFetch((url) => {\n paths.push(url)\n if (url.pathname.endsWith('/export/leads')) {\n expect(url.searchParams.get('state')).toBe('all')\n expect(url.searchParams.get('format')).toBe('json')\n return Response.json(Array.from({ length: 501 }, (_, index) => ({ _id: `lea-${index}`, custom: index })))\n }\n return fixture(url)\n })\n const value = pipeline()\n const destination = createMemoryDestination()\n expect((await runIngestion({ selected: selected(value, 'campaign_leads'), backfill: undefined }, { fetch, journal: createMemoryJournal(), destination, now, retry })).ok).toBe(true)\n expect(destination.tables.get('default.lemlist_campaign_leads_raw')).toHaveLength(501)\n expect(paths.map((url) => url.pathname)).toEqual(['/api/campaigns', '/api/v2/campaigns/cam/export/leads'])\n})\n\ntest('Lemlist full-contact hydration fails visibly when a discovered contact is unavailable', async () => {\n const fetch = lemlistFetch((url) => url.searchParams.has('idsOrEmails') ? Response.json([]) : fixture(url))\n const value = pipeline()\n const journal = createMemoryJournal()\n const result = await runIngestion({ selected: selected(value, 'contacts'), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })\n expect(result.ok).toBe(false)\n expect(result.streams[0]?.error).toContain('every discovered contact')\n expect((await journal.readCheckpoint('lemlist.fixture.contacts')).lastSuccessSeq).toBe(0)\n})\n\ntest('Lemlist scoped conversation users are snapshotted and pagination follows provider pages', async () => {\n const userIds = ['usr-selected']\n const config = { ...fixtureConfig, pageSize: 2, inboxUserIds: userIds }\n const urls: URL[] = []\n const fetch = lemlistFetch((url) => {\n urls.push(url)\n expect(url.pathname).toBe('/api/inbox')\n expect(url.searchParams.get('userId')).toBe('usr-selected')\n const page = Number(url.searchParams.get('page'))\n return inbox([{ _id: `conversation-${page}` }], { page, next: page === 1 ? 2 : null, total: 2, limit: 2 })\n })\n const value = createLemlistPipeline(config)\n userIds[0] = 'changed'\n config.pageSize = 100\n const destination = createMemoryDestination()\n expect((await runIngestion({ selected: selected(value, 'inbox_conversations'), backfill: undefined }, { fetch, journal: createMemoryJournal(), destination, now, retry })).ok).toBe(true)\n expect(urls.map((url) => [url.searchParams.get('page'), url.searchParams.get('limit')])).toEqual([['1', '2'], ['2', '2']])\n expect(destination.tables.get('default.lemlist_inbox_conversations_raw')?.map((row) => row.id)).toEqual([\n '[\"lemlist.fixture\",\"usr-selected\",\"conversation-1\"]', '[\"lemlist.fixture\",\"usr-selected\",\"conversation-2\"]',\n ])\n})\n\ntest('Lemlist messages revisit old contacts and use skip pagination without marking anything read', async () => {\n let body = 'before'\n const skips: string[] = []\n const fetch = lemlistFetch((url, init) => {\n expect(init?.method ?? 'GET').toBe('GET')\n if (url.pathname.startsWith('/api/inbox/')) {\n expect(url.searchParams.get('markAsRead')).toBe('false')\n expect(url.searchParams.has('minDate')).toBe(false)\n skips.push(url.searchParams.get('skip') ?? '')\n const page = url.searchParams.get('skip') === '0' ? 1 : 2\n return inbox([{ _id: `message-${page}`, createdAt: '2000-01-01', message: body }], { page, next: page === 1 ? 2 : null, total: 2, limit: 2 })\n }\n return listing([{ _id: 'ctc', createdAt: '2000-01-01' }], url)\n })\n const value = pipeline({ pageSize: 2 })\n const journal = createMemoryJournal()\n const destination = createMemoryDestination()\n const request = { selected: selected(value, 'inbox_messages'), backfill: undefined }\n expect((await runIngestion(request, { fetch, journal, destination, now, retry })).ok).toBe(true)\n body = 'edited reply'\n expect((await runIngestion(request, { fetch, journal, destination, now, retry })).ok).toBe(true)\n expect(skips).toEqual(['0', '2', '0', '2'])\n expect(destination.tables.get('default.lemlist_inbox_messages_raw')?.map((row) => row.raw)).toContainEqual({\n source_id: 'lemlist.fixture', contact_id: 'ctc', data: { _id: 'message-1', createdAt: '2000-01-01', message: 'edited reply' },\n })\n})\n\nfor (const resource of ['contacts', 'companies', 'campaign_leads', 'inbox_conversations', 'inbox_messages']) {\n test(`Lemlist ${resource} safely replays destination failure from its own discovery`, async () => {\n const paths: string[] = []\n const fetch = lemlistFetch((url) => { paths.push(url.pathname); return fixture(url) })\n const value = pipeline()\n const journal = createMemoryJournal()\n const request = { selected: selected(value, resource), backfill: undefined }\n expect((await runIngestion(request, { fetch, journal, destination: { insert: async () => { throw new Error('sink denied') } }, now, retry })).ok).toBe(false)\n expect((await journal.readCheckpoint(`lemlist.fixture.${resource}`)).lastSuccessSeq).toBe(0)\n const first = [...paths]\n paths.length = 0\n expect((await runIngestion(request, { fetch, journal, destination: createMemoryDestination(), now, retry })).ok).toBe(true)\n expect(paths).toEqual(first)\n })\n}\n\ntest('Lemlist empty full collections record completion without custom scan state', async () => {\n const fetch = lemlistFetch((url) => {\n if (url.pathname === '/api/contacts' || url.pathname === '/api/companies') {\n expect(url.searchParams.has('idsOrEmails')).toBe(false)\n return listing([], url)\n }\n if (url.pathname === '/api/team') return Response.json({ users: [{ userId: 'usr' }] })\n if (url.pathname === '/api/inbox') return inbox([])\n return Response.json([])\n })\n const value = pipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion({ selected: selected(value), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })).ok).toBe(true)\n for (const resource of resources) expect((await journal.readCheckpoint(`lemlist.fixture.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n})\n\nfor (const malformed of ['missing', 'repeated', 'truncated', 'invalid-export']) {\n test(`Lemlist rejects ${malformed} continuation/export without successful completion`, async () => {\n const resource = malformed === 'invalid-export' ? 'campaign_leads' : 'inbox_conversations'\n const fetch = lemlistFetch((url) => {\n if (malformed === 'invalid-export' && url.pathname.endsWith('/export/leads')) return Response.json({ data: [{ _id: 'capped' }], next: 'unknown' })\n if (url.pathname === '/api/inbox') {\n const page = Number(url.searchParams.get('page'))\n if (malformed === 'missing') return Response.json({ data: [], pagination: { totalItems: 0 } })\n return inbox([{ _id: `conversation-${page}` }], { page, next: malformed === 'repeated' ? page : null, total: 3 })\n }\n return fixture(url)\n })\n const value = pipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion({ selected: selected(value, resource), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })).ok).toBe(false)\n expect((await journal.readCheckpoint(`lemlist.fixture.${resource}`)).lastSuccessSeq).toBe(0)\n })\n}\n\nfor (const resource of ['contacts', 'companies']) {\n test(`Lemlist ${resource} consumes every advertised offset page`, async () => {\n const offsets: string[] = []\n const fetch = lemlistFetch((url) => {\n if (url.searchParams.has('idsOrEmails')) {\n const ids = url.searchParams.get('idsOrEmails')?.split(',') ?? []\n return Response.json(ids.map((_id) => ({ _id, fields: { custom: 'complete' } })))\n }\n offsets.push(url.searchParams.get('offset') ?? '')\n const offset = Number(url.searchParams.get('offset'))\n return listing(offset === 0 ? [{ _id: 'first' }, { _id: 'second' }] : [{ _id: 'last' }], url, 3)\n })\n const value = pipeline({ pageSize: 2 })\n const destination = createMemoryDestination()\n expect((await runIngestion({ selected: selected(value, resource), backfill: undefined }, { fetch, journal: createMemoryJournal(), destination, now, retry })).ok).toBe(true)\n expect(offsets).toEqual(['0', '2'])\n expect(destination.tables.get(`default.lemlist_${resource}_raw`)?.map((row) => row.id)).toEqual(\n ['first', 'second', 'last'].map((id) => JSON.stringify(['lemlist.fixture', id])))\n })\n}\n\ntest('Lemlist keeps distinct user inbox observations when native conversation IDs match', async () => {\n const fetch = lemlistFetch((url) => inbox([{ _id: 'shared', unread: url.searchParams.get('userId') === 'usr-a' }]))\n const value = pipeline({ inboxUserIds: ['usr-a', 'usr-b'] })\n const destination = createMemoryDestination()\n expect((await runIngestion({ selected: selected(value, 'inbox_conversations'), backfill: undefined }, { fetch, journal: createMemoryJournal(), destination, now, retry })).ok).toBe(true)\n expect(destination.tables.get('default.lemlist_inbox_conversations_raw')?.map((row) => [row.id, row.raw])).toEqual([\n ['[\"lemlist.fixture\",\"usr-a\",\"shared\"]', { source_id: 'lemlist.fixture', user_id: 'usr-a', data: { _id: 'shared', unread: true } }],\n ['[\"lemlist.fixture\",\"usr-b\",\"shared\"]', { source_id: 'lemlist.fixture', user_id: 'usr-b', data: { _id: 'shared', unread: false } }],\n ])\n})\n\ntest('Lemlist interrupted message traversal restarts contact discovery and skip zero', async () => {\n let fail = true\n const paths: string[] = []\n const fetch = lemlistFetch((url) => {\n paths.push(url.pathname + (url.searchParams.has('skip') ? `:${url.searchParams.get('skip')}` : ''))\n if (url.pathname === '/api/inbox/ctc') {\n const page = url.searchParams.get('skip') === '0' ? 1 : 2\n if (fail && page === 2) return new Response('denied', { status: 403 })\n return inbox([{ _id: `message-${page}` }], { page, next: page === 1 ? 2 : null, total: 2, limit: 2 })\n }\n return fixture(url)\n })\n const value = pipeline({ pageSize: 2 })\n const journal = createMemoryJournal()\n const request = { selected: selected(value, 'inbox_messages'), backfill: undefined }\n const destination = createMemoryDestination()\n expect((await runIngestion(request, { fetch, journal, destination, now, retry })).ok).toBe(false)\n expect((await journal.readCheckpoint('lemlist.fixture.inbox_messages')).lastSuccessSeq).toBe(0)\n fail = false\n expect((await runIngestion(request, { fetch, journal, destination, now, retry })).ok).toBe(true)\n expect(paths).toEqual(['/api/contacts', '/api/inbox/ctc:0', '/api/inbox/ctc:2', '/api/contacts', '/api/inbox/ctc:0', '/api/inbox/ctc:2'])\n})\n\ntest('Lemlist refuses a shortened contact listing that still advertises more records', async () => {\n const fetch = lemlistFetch((url) => listing([{ _id: 'first' }], url, 3))\n const value = pipeline({ pageSize: 2 })\n const journal = createMemoryJournal()\n expect((await runIngestion({ selected: selected(value, 'contacts'), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })).ok).toBe(false)\n expect((await journal.readCheckpoint('lemlist.fixture.contacts')).lastSuccessSeq).toBe(0)\n})\n\nfor (const resource of ['contacts', 'companies', 'inbox_conversations']) {\n test(`Lemlist ${resource} refuses partially overlapping pages despite matching advertised totals`, async () => {\n const fetch = lemlistFetch((url) => {\n if (url.searchParams.has('idsOrEmails')) return Response.json((url.searchParams.get('idsOrEmails')?.split(',') ?? []).map((_id) => ({ _id })))\n const first = resource === 'inbox_conversations' ? url.searchParams.get('page') === '1' : url.searchParams.get('offset') === '0'\n const items = first ? [{ _id: 'a' }, { _id: 'b' }] : [{ _id: 'b' }, { _id: 'c' }]\n return resource === 'inbox_conversations'\n ? inbox(items, { page: first ? 1 : 2, next: first ? 2 : null, total: 4, limit: 2 })\n : listing(items, url, 4)\n })\n const value = pipeline({ pageSize: 2, inboxUserIds: ['usr'] })\n const journal = createMemoryJournal()\n const result = await runIngestion({ selected: selected(value, resource), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry })\n expect(result.ok).toBe(false)\n expect(result.streams[0]?.error).toContain('object ID')\n expect((await journal.readCheckpoint(`lemlist.fixture.${resource}`)).lastSuccessSeq).toBe(0)\n })\n}\n\ntest('Lemlist fails a missing API key in every stream before any request without retrying', async () => {\n let requests = 0\n const journal = createMemoryJournal()\n const value = createLemlistPipeline({ ...fixtureConfig, apiKey: undefined })\n const result = await runIngestion({ selected: selectStreams([value], []), backfill: undefined }, { fetch: lemlistFetch(() => { requests += 1; return Response.json([]) }), journal, destination: createMemoryDestination(), now })\n expect(result.streams).toHaveLength(7)\n expect(result.streams.every((stream) => stream.outcome === 'failed' && stream.error?.includes('Set LEMLIST_API_KEY or pass apiKey.'))).toBe(true)\n expect(requests).toBe(0)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n})\n\ntest('Lemlist checks its configuration when a stream runs, not when the module loads or a stream is selected', async () => {\n let requests = 0\n const value = createLemlistPipeline({ ...fixtureConfig, pageSize: 500, start: new Date(Number.NaN), intervalMs: 0, inboxUserIds: ['usr', 'usr'] })\n const streams = selectStreams([value], [])\n expect(streams).toHaveLength(7)\n const result = await runIngestion({ selected: streams, backfill: undefined }, { fetch: lemlistFetch(() => { requests += 1; return Response.json([]) }), journal: createMemoryJournal(), destination: createMemoryDestination(), now })\n expect(result.streams).toHaveLength(7)\n expect(result.streams.every((stream) => stream.outcome === 'failed')).toBe(true)\n const activities = result.streams.find((stream) => stream.streamId.endsWith('.activities'))\n const others = result.streams.filter((stream) => stream !== activities)\n expect(activities?.error).toBe('timestampWindow: start must be a valid Date.')\n expect(others.every((stream) => /at pageSize[\\s\\S]*at start[\\s\\S]*at intervalMs[\\s\\S]*at inboxUserIds/.test(stream.error ?? ''))).toBe(true)\n expect(requests).toBe(0)\n})\n\ntest('Lemlist fails a malformed provider payload at once and retries only a transient response', async () => {\n const run = async (companies: (url: URL) => Response) => {\n const fetch = lemlistFetch((url) => url.pathname === '/api/companies' ? companies(url) : fixture(url))\n const value = pipeline()\n const journal = createMemoryJournal()\n const result = await runIngestion({ selected: selectStreams([value], ['resource:companies']), backfill: undefined }, { fetch, journal, destination: createMemoryDestination(), now, retry: { retries: 2, minTimeout: 0 } })\n return { result, retries: journal.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => event.errorClass) }\n }\n\n let calls = 0\n const malformed = await run((url) => { calls += 1; return Response.json({ data: 'not-a-list', total: 0, limit: 100, offset: Number(url.searchParams.get('offset')) }) })\n expect(malformed.result.streams[0]?.outcome).toBe('failed')\n expect(malformed.result.streams[0]?.error).toContain('Invalid input: expected array, received string')\n expect(calls).toBe(1)\n expect(malformed.retries).toEqual([])\n\n let unavailable = true\n const flaky = await run((url) => {\n if (unavailable) { unavailable = false; return new Response('busy', { status: 503 }) }\n return fixture(url)\n })\n expect(flaky.result.ok).toBe(true)\n expect(flaky.retries).toEqual(['transient'])\n})\n" } ], "meta": { "chkit": { "formatVersion": 1, "version": "0.3.0", "changelog": [ { "version": "0.3.0", "changes": [ "Read configuration and the API key when a stream runs, so `generate`, `migrate`, and `chkit check` never depend on them; invalid settings or a missing key fail that run before any request. Requires zod 4 and chkit 0.2.0-beta.12.", "Send requests through the ingestion runtime, which retries only network failures, timeouts, and retryable HTTP statuses such as 429; malformed responses, inconsistent pagination, and invalid checkpoints fail at once.", "Set `apiKey` in the configuration to use another key, for example for a second account; it defaults to `LEMLIST_API_KEY`." ] }, { "version": "0.2.1", "changes": [ "Clarify that raw records use ClickHouse native JSON normalization, which can omit explicit null properties and empty objects rather than preserving exact response text." ] }, { "version": "0.2.0", "changes": [ "Sync seven independent raw resources: campaigns, contacts, companies, campaign leads, activities, inbox conversations, and inbox messages.", "Preserve bounded overlapping activity intervals, acknowledgement-only progress, explicit backfill recovery, and existing campaign/activity identities.", "Hydrate complete same-resource contacts in bounded ID batches and export all campaign leads rather than using the nonpaginating 500-record list.", "Independently discover campaigns, contacts, and inbox users; paginate accessible message history with markAsRead=false and preserve native records in scoped envelopes.", "Use ordinary full-sync completion and safe replay for six resources without reliable modification filters; validate continuations, totals, empty completion, and source/destination recovery.", "Add five raw tables with source/parent-scoped row identities and portable fixtures; preserve version 0.1.0 history and document additive migration, polling, and deletion limits.", "Consume the ingestion plugin's full pagination pages, preserving continuations and empty terminal pages with independent resource checkpoints." ] }, { "version": "0.1.0", "changes": [ "Introduce raw campaigns and activities ingestion." ] } ], "language": "typescript", "license": "MIT", "documentation": "https://chkit.obsessiondb.com/integrations/lemlist/", "logo": "https://chkit.obsessiondb.com/logos/lemlist.svg", "authentication": { "method": "HTTP Basic API key", "env": [ "LEMLIST_API_KEY" ], "setup": [ "Provide LEMLIST_API_KEY with read access to the selected resources.", "Keep the API key in the runtime environment and rotate it according to the provider policy." ], "documentation": "https://developer.lemlist.com/" }, "chkit": "^0.2.0-beta.12", "ingest": "^0.2.0-beta.12", "clickhouse": ">=25.3.0", "root": "src/integrations/lemlist", "entry": "index.ts", "exports": [ "lemlistPipeline", "createLemlistPipeline", "lemlist_activitiesRaw", "lemlist_campaignsRaw", "lemlist_contactsRaw", "lemlist_companiesRaw", "lemlist_campaignLeadsRaw", "lemlist_inboxConversationsRaw", "lemlist_inboxMessagesRaw" ], "resources": [ { "name": "activities", "title": "Activities", "table": "lemlist_activities_raw", "description": "Outreach activity events", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "GET", "path": "/activities", "documentation": "https://developer.lemlist.com/api-reference/endpoints/activities/get-many-activities" } ] }, { "name": "campaigns", "title": "Campaigns", "table": "lemlist_campaigns_raw", "description": "Campaign metadata", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/campaigns", "documentation": "https://developer.lemlist.com/api-reference/endpoints/campaigns/get-many-campaigns" } ] }, { "name": "contacts", "title": "Contacts", "table": "lemlist_contacts_raw", "description": "Complete team-wide contact records and native campaign lead references", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/contacts", "documentation": "https://developer.lemlist.com/api-reference/endpoints/contacts/get-many-contacts" } ] }, { "name": "companies", "title": "Companies", "table": "lemlist_companies_raw", "description": "Company records and native custom fields", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/companies", "documentation": "https://developer.lemlist.com/api-reference/endpoints/companies/get-many-companies" } ] }, { "name": "campaign_leads", "title": "Campaign leads", "table": "lemlist_campaign_leads_raw", "description": "Complete campaign-specific lead exports with campaign scope", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/campaigns", "documentation": "https://developer.lemlist.com/api-reference/endpoints/campaigns/get-many-campaigns" }, { "method": "GET", "path": "/v2/campaigns/{campaignId}/export/leads", "documentation": "https://developer.lemlist.com/api-reference/endpoints/campaigns/export-campaign-leads-v2" } ] }, { "name": "inbox_conversations", "title": "Inbox conversations", "table": "lemlist_inbox_conversations_raw", "description": "Conversations with independent user inbox scope", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/team", "documentation": "https://developer.lemlist.com/api-reference/endpoints/team/get-team" }, { "method": "GET", "path": "/inbox", "documentation": "https://developer.lemlist.com/api-reference/endpoints/inbox/get-many-inboxes" } ] }, { "name": "inbox_messages", "title": "Inbox messages", "table": "lemlist_inbox_messages_raw", "description": "Complete accessible per-contact message history without marking conversations read", "scopes": [], "strategy": "full", "endpoints": [ { "method": "GET", "path": "/contacts", "documentation": "https://developer.lemlist.com/api-reference/endpoints/contacts/get-many-contacts" }, { "method": "GET", "path": "/inbox/{contactId}", "documentation": "https://developer.lemlist.com/api-reference/endpoints/inbox/get-contact-messages" } ] } ], "views": [], "sync": { "description": "Activities checkpoint acknowledged creation-time intervals; six other resources record independent full-read completion and replay mutable pagination from the beginning.", "schedule": "Run bunx chkit ingest run --tag provider:lemlist from a scheduler.", "deletions": "Missing records are not deleted automatically. Activities need historical reconciliation for older metadata edits; other resources revisit current accessible parents on each full read." }, "env": { "LEMLIST_API_KEY": "" }, "fileHashes": { "src/integrations/lemlist/README.md": "c356a9c511029fe6e23676fae86f3fdf1fc068ceefa0b20c0284cb95a49eafc1", "src/integrations/lemlist/index.ts": "6aa65944e2753412999d1833215145d0aaa5ed8978647d96f9711ed014de6393", "src/integrations/lemlist/config.ts": "56d78f3e4d8453240b2bc0d944116537466d2baccb9e287e60bd6dcccbe0907b", "src/integrations/lemlist/client.ts": "297040e2bcdc11004de80971d61e8a2cd438c80a10c4e2758225a9476943b8ba", "src/integrations/lemlist/pipeline.ts": "2c24f5f79d9572fd6c585cce4f09460917d1b1ead2cc13b7aa2d9e213806bc5a", "src/integrations/lemlist/sources/activities.ts": "2bd63c61452a13c307726c506a286e10306145511792565a186be85f60588fae", "src/integrations/lemlist/sources/campaigns.ts": "35cba2f3a4c23e4fdcc6775d97d0741514d6467d24d526313363d692888edb8d", "src/integrations/lemlist/tests/basic.test.ts": "e9f42d56e17ea51d44e2c342eb85cb19f5c961b2db4435d4bdbac7721249e954", "src/integrations/lemlist/sources/contacts.ts": "2b85da4ab7d92bf793e4dec39c92d0539d614637fe4b3c02af239337e1f39cad", "src/integrations/lemlist/sources/companies.ts": "55cf19f888396442ee65847c61096a1c4aef45ec3ecd8100edc3e58d5aaa8952", "src/integrations/lemlist/sources/campaign-leads.ts": "64987feb66312be7877199ed78e1f16d7ab808c7b0e9cbbbc636ab877dcefc6c", "src/integrations/lemlist/sources/inbox-conversations.ts": "d00347ecd0c0e1d41096379172d5a2f90a5eb3aea85d2fc1827a16f9f25f6f26", "src/integrations/lemlist/sources/inbox-messages.ts": "0c94945ddec84c5cd48e5ebcab98499303aa3a2de77fb3f53eee92d116230155", "src/integrations/lemlist/tests/resources.test.ts": "635a90618cec9f668665e93d1aa76982ff370ecad177421d6ecd7576c84e8339" } } } }