@walkeros/server-destination-gcp 4.8.1 → 4.8.2
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/CHANGELOG.md +25 -0
- package/README.md +4 -1
- package/dist/dev.d.mts +16 -3
- package/dist/dev.d.ts +16 -3
- package/dist/dev.js +1 -1
- package/dist/dev.js.map +1 -1
- package/dist/dev.mjs +1 -1
- package/dist/dev.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/schemas.js +1 -1
- package/dist/schemas.js.map +1 -1
- package/dist/schemas.mjs +1 -1
- package/dist/schemas.mjs.map +1 -1
- package/dist/walkerOS.json +486 -135
- package/package.json +4 -4
package/dist/dev.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bigquery/examples/index.ts","../src/bigquery/examples/env.ts","../src/bigquery/__mocks__/@google-cloud/bigquery-storage.ts","../src/bigquery/examples/step.ts","../src/bigquery/eventToRow.ts","../src/pubsub/examples/index.ts","../src/pubsub/examples/env.ts","../src/pubsub/examples/step.ts","../src/bigquery/schemas/index.ts","../src/bigquery/schemas/settings.ts","../src/bigquery/schemas/mapping.ts","../src/pubsub/schemas/index.ts","../src/pubsub/schemas/settings.ts","../src/pubsub/schemas/mapping.ts","../src/pubsub/schemas/setup.ts","../src/schemas.ts","../src/hints.ts","../src/dev.ts"],"sourcesContent":["export * as env from './env';\nexport * as step from './step';\n","import type { Env, QueryClient, TableMetadataShape } from '../types';\nimport {\n managedwriter as mockManagedwriter,\n adapt as mockAdapt,\n} from '../__mocks__/@google-cloud/bigquery-storage';\n\n/**\n * Example environment configurations for GCP BigQuery destination\n *\n * These environments provide standardized mock structures for testing\n * and development without requiring actual BigQuery SDK dependencies.\n *\n * The Storage Write API mocks (WriterClient, JSONWriter, adapt) are\n * re-exported from the package-local __mocks__ folder so example/test\n * code shares a single source of truth with the jest auto-mock.\n */\n\n/**\n * Mock BigQuery query client: dataset and table provisioning calls resolve as\n * if both already exist.\n */\nfunction createMockBigQuery() {\n return class MockBigQuery implements QueryClient {\n calls: Array<{ method: string; args: unknown[] }>;\n options: unknown;\n\n constructor(options?: unknown) {\n this.options = options;\n this.calls = [];\n }\n\n dataset(datasetId: string) {\n this.calls.push({ method: 'dataset', args: [datasetId] });\n return this;\n }\n\n table(tableId: string) {\n this.calls.push({ method: 'table', args: [tableId] });\n return this;\n }\n\n async exists(): Promise<[boolean]> {\n this.calls.push({ method: 'exists', args: [] });\n return [true];\n }\n\n async create(options: unknown): Promise<void> {\n this.calls.push({ method: 'create', args: [options] });\n }\n\n async getMetadata(): Promise<[TableMetadataShape]> {\n this.calls.push({ method: 'getMetadata', args: [] });\n return [{}];\n }\n };\n}\n\n/**\n * Standard mock environment for push operations\n *\n * Use this for testing BigQuery Storage Write appends without connecting\n * to actual GCP infrastructure.\n */\nexport const push: Env = {\n get BigQuery() {\n return createMockBigQuery();\n },\n get WriterClient() {\n return mockManagedwriter.WriterClient;\n },\n get JSONWriter() {\n return mockManagedwriter.JSONWriter;\n },\n get adapt() {\n return mockAdapt;\n },\n};\n\n/**\n * Every row goes through the writer's `appendRows`; the writer is built from\n * `JSONWriter` in init, so the path continues on the constructed instance.\n * Constructors are not recorded: their arguments carry credentials.\n */\nexport const simulation = ['call:JSONWriter.appendRows'];\n","import { EventEmitter } from 'events';\n\nconst calls: Array<{ method: string; args: unknown[] }> = [];\n\ninterface MockRowError {\n index: number;\n code: number;\n message: string;\n}\n\nlet nextAppendRowErrors: MockRowError[] | null = null;\nlet nextAppendThrow: unknown = null;\nlet nextGetResultReject: unknown = null;\nlet nextCreateStreamConnectionError: unknown = null;\n\n/**\n * Honest stand-in for the SDK's StreamConnection: a REAL Node EventEmitter so\n * `emit('error', …)` with no listener throws exactly like the real one (Node's\n * special-cased `'error'` event). `onConnectionError` mirrors the SDK surface:\n * it registers an `'error'` listener and returns an `{ off }` disposable.\n */\nclass MockStreamConnection extends EventEmitter {\n private readonly streamId: string;\n constructor(streamId: string) {\n super();\n this.streamId = streamId;\n }\n getStreamId(): string {\n return this.streamId;\n }\n onConnectionError(listener: (err: unknown) => void): { off: () => void } {\n calls.push({ method: 'onConnectionError', args: [] });\n this.on('error', listener);\n return {\n off: () => {\n this.off('error', listener);\n },\n };\n }\n /**\n * Test-only: literally `this.emit('error', err)` with NO internal\n * listener-count guard, so before a listener is attached this reproduces\n * Node's real \"throw if no 'error' listener\" behavior. A fake that silently\n * swallowed would mask the very crash this listener exists to contain.\n */\n __emitConnectionError(err: unknown): void {\n this.emit('error', err);\n }\n}\n\n// The most recently created connection, so tests can emit on it and assert the\n// listener was registered.\nlet lastConnection: MockStreamConnection | null = null;\n\n// Every connection ever created (this reset cycle), so tests can assert that a\n// concurrent re-open did not orphan a connection still carrying an 'error'\n// listener.\nconst allConnections: MockStreamConnection[] = [];\n\nclass MockJSONWriter {\n constructor(_args: { connection: unknown; protoDescriptor: unknown }) {\n calls.push({ method: 'JSONWriter.ctor', args: [_args] });\n }\n appendRows(rows: unknown[], offsetValue?: unknown) {\n calls.push({ method: 'appendRows', args: [rows, offsetValue] });\n const queuedThrow = nextAppendThrow;\n if (queuedThrow !== null) {\n nextAppendThrow = null;\n throw queuedThrow;\n }\n const queuedErrors = nextAppendRowErrors;\n nextAppendRowErrors = null;\n const queuedReject = nextGetResultReject;\n nextGetResultReject = null;\n return {\n getResult: async () => {\n // Models a gRPC deadline-exceeded (or any stream error): the append is\n // accepted but getResult() rejects when the stream's deadline fires.\n if (queuedReject !== null) throw queuedReject;\n return {\n appendResult: { offset: { value: '0' } },\n rowErrors: queuedErrors ?? [],\n writeStream: 'projects/p/datasets/d/tables/t/streams/_default',\n };\n },\n };\n }\n close(): void {\n calls.push({ method: 'JSONWriter.close', args: [] });\n }\n}\n\nclass MockWriterClient {\n constructor(args: {\n projectId?: string;\n keyFilename?: string;\n credentials?: unknown;\n scopes?: string | string[];\n }) {\n calls.push({ method: 'WriterClient.ctor', args: [args] });\n }\n async createStreamConnection(\n args: {\n destinationTable: string;\n streamId: string;\n },\n options?: unknown,\n ) {\n // Match the real SDK: callers must pass streamId=DefaultStream (not streamType)\n // for default-stream use. Passing streamType triggers a CreateWriteStream\n // call with type='DEFAULT', which BQ rejects as TYPE_UNSPECIFIED.\n if (args.streamId !== 'DEFAULT') {\n throw new Error(\n `mock createStreamConnection: expected streamId='DEFAULT', got ${JSON.stringify(args)}`,\n );\n }\n // args[1] captures the gax CallOptions (e.g. { timeout }) so tests can\n // assert the request deadline is forwarded to the appendRows stream.\n calls.push({ method: 'createStreamConnection', args: [args, options] });\n const queuedError = nextCreateStreamConnectionError;\n if (queuedError !== null) {\n nextCreateStreamConnectionError = null;\n throw queuedError;\n }\n const connection = new MockStreamConnection(\n `${args.destinationTable}/streams/_default`,\n );\n lastConnection = connection;\n allConnections.push(connection);\n return connection;\n }\n async getWriteStream(\n args: { streamId: string; view?: number },\n options?: unknown,\n ) {\n // args[1] captures the gax CallOptions so tests can assert the deadline\n // is forwarded to the unary schema fetch.\n calls.push({ method: 'getWriteStream', args: [args, options] });\n // Minimal tableSchema shape consumed by adapt.convertStorageSchemaToProto2Descriptor\n return {\n tableSchema: { fields: [] },\n };\n }\n close(): void {\n calls.push({ method: 'WriterClient.close', args: [] });\n }\n}\n\nconst adapt = {\n convertStorageSchemaToProto2Descriptor: (_schema: unknown, _root: string) => {\n calls.push({\n method: 'adapt.convertStorageSchemaToProto2Descriptor',\n args: [_schema, _root],\n });\n return { name: 'root', field: [] };\n },\n};\n\nconst managedwriter = {\n WriterClient: MockWriterClient,\n JSONWriter: MockJSONWriter,\n DefaultStream: 'DEFAULT',\n};\n\nconst protos = {\n google: {\n cloud: {\n bigquery: {\n storage: {\n v1: {\n WriteStreamView: {\n WRITE_STREAM_VIEW_UNSPECIFIED: 0,\n BASIC: 1,\n FULL: 2,\n },\n },\n },\n },\n },\n },\n};\n\n// Test-only helper. Not part of the real SDK.\nfunction __getMockCalls() {\n return calls;\n}\n\nfunction __resetMockCalls() {\n calls.length = 0;\n nextAppendRowErrors = null;\n nextAppendThrow = null;\n nextGetResultReject = null;\n nextCreateStreamConnectionError = null;\n lastConnection = null;\n allConnections.length = 0;\n}\n\n/**\n * Test-only: the most recently created StreamConnection, so a test can emit an\n * out-of-band `'error'` on it (via `__emitConnectionError`) and assert the\n * destination attached a listener.\n */\nfunction __getLastConnection(): MockStreamConnection {\n if (!lastConnection) throw new Error('mock: no StreamConnection created yet');\n return lastConnection;\n}\n\n/**\n * Test-only: every StreamConnection created since the last reset, so a test can\n * assert that a concurrent re-open did not orphan a connection that still\n * carries an 'error' listener (a leak).\n */\nfunction __getAllConnections(): MockStreamConnection[] {\n return allConnections.slice();\n}\n\n/**\n * Test-only: queue rowErrors for the next appendRows().getResult() call.\n * Auto-resets after one use.\n */\nfunction __setNextAppendRowErrors(errors: MockRowError[]): void {\n nextAppendRowErrors = errors;\n}\n\n/**\n * Test-only: make the next appendRows() throw synchronously, simulating a\n * Storage Write API call failure. Auto-resets after one use.\n */\nfunction __setNextAppendThrow(err: unknown): void {\n nextAppendThrow = err;\n}\n\n/**\n * Test-only: make the next appendRows().getResult() reject, simulating a gRPC\n * deadline-exceeded (or any stream error) surfacing through the pending write.\n * Auto-resets after one use.\n */\nfunction __setNextGetResultReject(err: unknown): void {\n nextGetResultReject = err;\n}\n\n/**\n * Test-only: queue an error for the next createStreamConnection() call so\n * tests can simulate openWriter failures (NotFound, INVALID_ARGUMENT, etc.).\n * Auto-resets after one use.\n */\nfunction __setNextOpenWriterError(err: unknown): void {\n nextCreateStreamConnectionError = err;\n}\n\nexport {\n managedwriter,\n adapt,\n protos,\n MockStreamConnection,\n __getMockCalls,\n __resetMockCalls,\n __getLastConnection,\n __getAllConnections,\n __setNextAppendRowErrors,\n __setNextAppendThrow,\n __setNextGetResultReject,\n __setNextOpenWriterError,\n};\n","import type { Flow, WalkerOS } from '@walkeros/core';\nimport { getEvent } from '@walkeros/core';\nimport { eventToRow } from '../eventToRow';\n\n/**\n * Mirror of push.ts via eventToRow() -- produces a flat 15-column row\n * with nested object/array values JSON-stringified. Imported directly\n * from the runtime helper so the step examples stay in sync with what\n * push.ts actually emits to JSONWriter.appendRows.\n */\nfunction expectedRow(event: WalkerOS.Event) {\n return eventToRow(event);\n}\n\n/**\n * Page view -- one row appended through JSONWriter.appendRows([row]).\n * Captured as a single intent-level call: ['appendRows', [row]].\n */\nconst pageViewEvent = getEvent('page view', {\n timestamp: 1700001100,\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n source: { type: 'express', platform: 'server' },\n});\n\nexport const pageView: Flow.StepExample = {\n title: 'Page view',\n description:\n 'A page view is appended as one row through the BigQuery Storage Write API JSONWriter. Nested objects/arrays in data, source, etc. are JSON-stringified by eventToRow.',\n in: pageViewEvent,\n mapping: undefined,\n out: [['appendRows', [expectedRow(pageViewEvent)]]],\n};\n\n/**\n * Purchase -- nested array in data.items is JSON.stringified into the\n * data column of the appended row.\n */\nconst purchaseEvent = getEvent('order complete', {\n timestamp: 1700001101,\n data: {\n id: 'ORD-500',\n total: 199.99,\n items: [{ sku: 'SKU-1', qty: 2 }],\n },\n source: { type: 'express', platform: 'server' },\n});\n\nexport const purchase: Flow.StepExample = {\n title: 'Purchase',\n description:\n 'An order event is appended as a single row through JSONWriter.appendRows. The entire nested data object (including arrays like items) is JSON-stringified into the data column via eventToRow().',\n in: purchaseEvent,\n mapping: undefined,\n out: [['appendRows', [expectedRow(purchaseEvent)]]],\n};\n","import type { WalkerOS } from '@walkeros/core';\n\n/** Row shape passed to JSONWriter.appendRows. Values are JSON-serializable scalars or strings. */\nexport interface BigQueryRow {\n [key: string]: string | number | null;\n name: string;\n data: string | null;\n context: string | null;\n globals: string | null;\n custom: string | null;\n user: string | null;\n nested: string | null;\n consent: string | null;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n source: string | null;\n}\n\nfunction jsonOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'object') {\n if (Array.isArray(value) && value.length === 0) return null;\n if (!Array.isArray(value) && Object.keys(value).length === 0) return null;\n return JSON.stringify(value);\n }\n return JSON.stringify(value);\n}\n\n/** Convert a walkerOS Event v4 into a 15-column BigQuery row in canonical order.\n *\n * Note: BQ Storage Write API encodes TIMESTAMP fields as INT64 microseconds\n * since epoch (the SDK calls Long.fromString on the value). ISO strings fail\n * with \"interior hyphen\" because Long.fromString sees the date hyphens as\n * non-numeric. Pass microseconds directly.\n */\nexport function eventToRow(event: WalkerOS.Event): BigQueryRow {\n return {\n name: event.name,\n data: jsonOrNull(event.data),\n context: jsonOrNull(event.context),\n globals: jsonOrNull(event.globals),\n custom: jsonOrNull(event.custom),\n user: jsonOrNull(event.user),\n nested: jsonOrNull(event.nested),\n consent: jsonOrNull(event.consent),\n id: event.id,\n trigger: event.trigger,\n entity: event.entity,\n action: event.action,\n timestamp: new Date(event.timestamp).getTime() * 1000, // microseconds since epoch\n timing: event.timing,\n source: jsonOrNull(event.source),\n };\n}\n","export * as env from './env';\nexport * as step from './step';\n","import type {\n Env,\n PubSubPublisher,\n PublishMessage,\n TopicPublisher,\n} from '../types';\n\n/**\n * Example environment for the GCP Pub/Sub destination.\n *\n * `push` is the mock env simulate injects: `PubSub` builds a client whose\n * topics answer `publishMessage` locally, so nothing reaches GCP. Unit tests\n * still substitute the SDK module-wide via `jest.mock('@google-cloud/pubsub')`.\n */\n\nclass MockTopic implements TopicPublisher {\n constructor(public name: string) {}\n publishMessage(_message: PublishMessage): Promise<string> {\n return Promise.resolve('mock-message-id');\n }\n resumePublishing(_orderingKey: string): void {}\n}\n\nclass MockPubSub implements PubSubPublisher {\n constructor(public options?: object) {}\n topic(name: string): TopicPublisher {\n return new MockTopic(name);\n }\n close(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nexport const push: Env = {\n PubSub: MockPubSub,\n};\n\n/** The publish carries the request; `args[0]` is the message. */\nexport const simulation = ['call:PubSub.topic.publishMessage'];\n","import type { Flow, WalkerOS } from '@walkeros/core';\nimport { getEvent } from '@walkeros/core';\n\n// Build-time version define. The upstream collector stamps source.release with\n// this on push, so the expected payload must mirror it rather than a literal,\n// else it breaks whenever the fixed version group is bumped (release).\ndeclare const __VERSION__: string;\n\n/**\n * Pub/Sub step examples. Each example's `out` is the array of recorded mock\n * calls produced by `push()`. The recording shape is:\n * ['topic', topicName, topicOptions] // implicit topic-handle creation\n * ['publishMessage', topicName, messageOptions]\n * ['resumePublishing', topicName, orderingKey] // only on publish failure\n */\n\n// Events reaching a server destination arrive already enriched by the upstream\n// collector, so they carry the run trace and per-run count. The collector\n// preserves these (stamp-if-absent), keeping the example deterministic.\nconst orderEvent = getEvent('order complete', {\n timestamp: 1700001100,\n data: { id: 'ORD-500', total: 199.99, currency: 'EUR' },\n user: { id: 'usr-789' },\n source: {\n type: 'express',\n platform: 'server',\n trace: '1a2b3c4d5e6f70819a2b3c4d5e6f7081',\n count: 1,\n },\n});\n\nconst pageEvent = getEvent('page view', {\n timestamp: 1700001101,\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n source: {\n type: 'express',\n platform: 'server',\n trace: '9f8e7d6c5b4a39281706f5e4d3c2b1a0',\n count: 1,\n },\n});\n\nfunction expectedPayload(event: WalkerOS.Event): Buffer {\n // The harness pushes the event through an unconfigured collector, which stamps\n // source.release = { [name ?? platform ?? 'default']: __VERSION__ }. With no\n // collector name, the key is the event's platform. Mirror that here so the\n // expected message body matches the published (post-collector) event.\n const releaseKey = event.source.platform ?? 'default';\n const stamped = {\n ...event,\n source: { ...event.source, release: { [releaseKey]: __VERSION__ } },\n };\n return Buffer.from(JSON.stringify(stamped));\n}\n\n/**\n * Default publish, no mapping. Settings.topic = 'events'. The destination\n * constructs a topic handle inline with messageOrdering=false (no ordering\n * key resolved) and publishes the full event JSON as the message body.\n */\nexport const defaultPush: Flow.StepExample = {\n title: 'Default publish',\n description:\n 'An event is published to the configured Pub/Sub topic with the full JSON event as the message body and no ordering key.',\n in: orderEvent,\n out: [\n ['topic', 'events', { messageOrdering: false }],\n ['publishMessage', 'events', { data: expectedPayload(orderEvent) }],\n ],\n};\n\n/**\n * Per-rule topic override. Mapping carries `settings.topic = 'orders'`\n * which routes this rule to a dedicated topic.\n */\nexport const mappedTopic: Flow.StepExample = {\n title: 'Topic override',\n description:\n 'A mapping rule overrides the destination default topic so order events are published to a dedicated topic.',\n in: orderEvent,\n mapping: {\n settings: {\n topic: 'orders',\n },\n },\n out: [\n ['topic', 'orders', { messageOrdering: false }],\n ['publishMessage', 'orders', { data: expectedPayload(orderEvent) }],\n ],\n};\n\n/**\n * Per-rule ordering key resolved from the event. `mapping.orderingKey =\n * 'user.id'` is a Mapping.Value that resolves to the event's user.id. The\n * topic handle is constructed with messageOrdering=true and the publish\n * carries the resolved orderingKey.\n */\nexport const mappedOrderingKey: Flow.StepExample = {\n title: 'Ordering key from user',\n description:\n 'A mapping resolves the ordering key from event.user.id, enabling per-user ordering for this publish.',\n in: orderEvent,\n mapping: {\n settings: {\n orderingKey: 'user.id',\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: true }],\n [\n 'publishMessage',\n 'events',\n {\n data: expectedPayload(orderEvent),\n orderingKey: 'usr-789',\n },\n ],\n ],\n};\n\n/**\n * Per-rule attributes. `mapping.attributes = { entity: 'entity', action:\n * 'action' }` is a Mapping.Map resolved per event. Each value is a path\n * resolved against the event.\n */\nexport const mappedAttributes: Flow.StepExample = {\n title: 'Mapped attributes',\n description:\n 'A mapping resolves a per-event attribute map, here exposing entity and action as Pub/Sub attributes for routing in subscribers.',\n in: orderEvent,\n mapping: {\n settings: {\n attributes: {\n entity: 'entity',\n action: 'action',\n },\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: false }],\n [\n 'publishMessage',\n 'events',\n {\n data: expectedPayload(orderEvent),\n attributes: { entity: 'order', action: 'complete' },\n },\n ],\n ],\n};\n\n/**\n * Mapped data. `mapping.data` rewrites the publish body. The rewritten\n * object replaces the event as the message data.\n */\nexport const mappedData: Flow.StepExample = {\n title: 'Mapped payload',\n description:\n 'A data mapping transforms the event payload before publish. The rewritten object becomes the Pub/Sub message body.',\n in: orderEvent,\n mapping: {\n data: {\n map: {\n order_id: 'data.id',\n revenue: 'data.total',\n currency: 'data.currency',\n },\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: false }],\n [\n 'publishMessage',\n 'events',\n {\n // Mapped-data publish: the body is the mapping result (no event\n // envelope, so no source.release), emitted verbatim.\n data: Buffer.from(\n JSON.stringify({\n order_id: 'ORD-500',\n revenue: 199.99,\n currency: 'EUR',\n }),\n ),\n },\n ],\n ],\n};\n\n/**\n * Page view, no rule. Verifies free-form publish on a non-ordered topic\n * for an event with no special mapping.\n */\nexport const pageView: Flow.StepExample = {\n title: 'Page view',\n description:\n 'A page view is published to the default topic with no ordering key, demonstrating the simplest publish path.',\n in: pageEvent,\n out: [\n ['topic', 'events', { messageOrdering: false }],\n ['publishMessage', 'events', { data: expectedPayload(pageEvent) }],\n ],\n};\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z.object({\n client: z\n .any()\n .describe(\n 'Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n datasetId: z\n .string()\n .min(1)\n .default('walkerOS')\n .describe(\n 'BigQuery dataset ID where events will be stored (like walker_events)',\n ),\n tableId: z\n .string()\n .min(1)\n .default('events')\n .describe('BigQuery table ID for event storage (like events)'),\n location: z\n .string()\n .default('EU')\n .describe('Geographic location for the BigQuery dataset (like US)'),\n bigquery: z\n .any()\n .describe(\n 'Additional BigQuery client configuration options (like { keyFilename: \"path/to/key.json\" })',\n )\n .optional(),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP BigQuery Mapping Schema\n * BigQuery has no event-level mapping configuration\n */\nexport const MappingSchema = z.object({});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\nimport { SetupSchema } from './setup';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\nexport { SetupSchema, type Setup } from './setup';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\nexport const setup = zodToSchema(SetupSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z.object({\n client: z\n .any()\n .describe(\n 'Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n topic: z\n .string()\n .min(1)\n .describe(\n 'Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK.',\n ),\n credentials: z\n .any()\n .describe(\n 'Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)',\n )\n .optional(),\n apiEndpoint: z\n .string()\n .describe(\n 'Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Mapping value resolved per-event. Truthy enables per-key ordering for the publish.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Default per-event attribute map merged into every published message. Mapping.Map shape.',\n )\n .optional(),\n});\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Mapping Schema\n *\n * Per-rule overrides for topic, orderingKey, and attributes.\n */\nexport const MappingSchema = z.object({\n topic: z\n .string()\n .describe(\n 'Per-rule topic override. Falls back to settings.topic if absent.',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Per-rule attribute Mapping.Map merged on top of settings.attributes.',\n )\n .optional(),\n});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Setup Schema\n *\n * Provisioning options for `walkeros setup destination.<id>`. Idempotent topic\n * creation. Subscription provisioning is owned by the source side.\n */\nexport const SetupSchema = z.object({\n messageStoragePolicy: z\n .object({\n allowedPersistenceRegions: z\n .array(z.string())\n .describe(\n 'Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).',\n ),\n })\n .describe('Topic-level message storage policy.')\n .optional(),\n messageRetentionDuration: z\n .object({\n seconds: z\n .number()\n .describe('Retention window in seconds. Default: project default.'),\n })\n .describe('Topic-level retention configuration.')\n .optional(),\n kmsKeyName: z\n .string()\n .describe('Customer-managed encryption key (CMEK) resource name. Optional.')\n .optional(),\n labels: z\n .record(z.string(), z.string())\n .describe('Topic labels for organization and billing.')\n .optional(),\n});\n\nexport type Setup = z.infer<typeof SetupSchema>;\n","// Browser-safe schema-only exports\n// This file exports ONLY schemas without any Node.js dependencies\nexport { settings, mapping } from './bigquery/schemas';\nexport {\n settings as pubsubSettings,\n mapping as pubsubMapping,\n setup as pubsubSetup,\n} from './pubsub/schemas';\n","import type { Hint } from '@walkeros/core';\n\nexport const hints: Hint.Hints = {\n 'auth-methods': {\n text: 'Supports three auth methods: SA key file via bigquery options ({ bigquery: { keyFilename: \"./sa.json\" } }), Application Default Credentials (automatic on GCP infrastructure — just provide projectId), or a pre-configured BigQuery client instance (client option). See settings schema for all options.',\n code: [\n {\n lang: 'json',\n code: '{ \"settings\": { \"projectId\": \"my-project\", \"bigquery\": { \"keyFilename\": \"./sa.json\" } } }',\n },\n {\n lang: 'json',\n code: '{ \"settings\": { \"projectId\": \"my-project\" } }',\n },\n ],\n },\n 'storage-format': {\n text: 'All events are stored in a single table. Scalar fields (strings, numbers, booleans) are stored as-is. Nested objects and arrays are JSON-stringified automatically. Defaults: dataset \"walkeros\", table \"events\", location \"EU\" — all overridable via settings.',\n },\n 'query-json-columns': {\n text: 'Nested event fields (data, context, globals, user) are stored as JSON strings. Use BigQuery JSON_EXTRACT_SCALAR to query them. Field paths follow the walkerOS event structure.',\n code: [\n {\n lang: 'sql',\n code: \"SELECT JSON_EXTRACT_SCALAR(data, '$.total') AS total FROM `project.walkeros.events` WHERE entity = 'order'\",\n },\n ],\n },\n 'troubleshoot-empty-table': {\n text: \"Events not appearing? Common causes: projectId doesn't match GCP project, dataset doesn't exist yet (create via BigQuery console or bq CLI before first push), or SA key lacks bigquery.dataEditor role. The destination validates client/datasetId/tableId at push time but GCP permission errors surface from the BigQuery SDK.\",\n },\n};\n","import * as bigqueryExamplesNs from './bigquery/examples';\nimport * as pubsubExamplesNs from './pubsub/examples';\nimport * as bigquerySchemasNs from './bigquery/schemas';\nimport * as pubsubSchemasNs from './pubsub/schemas';\n\nexport * as schemas from './schemas';\nexport * as examples from './bigquery/examples';\nexport * as pubsubExamples from './pubsub/examples';\nexport { hints } from './hints';\n\n/** Dev examples per export, keyed by the export names in package.json. */\nexport const exportExamples = {\n destinationBigQuery: bigqueryExamplesNs,\n destinationPubSub: pubsubExamplesNs,\n};\n\n/** Schemas per export, keyed by the export names in package.json. */\nexport const exportSchemas = {\n destinationBigQuery: {\n settings: bigquerySchemasNs.settings,\n mapping: bigquerySchemasNs.mapping,\n },\n destinationPubSub: {\n settings: pubsubSchemasNs.settings,\n mapping: pubsubSchemasN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zBM,IAAMC,YAAWC,aAAYC,eAAc;AAC3C,IAAMC,WAAUF,aAAYG,cAAa;AACzC,IAAM,QAAQH,aAAY,WAAW;;;AIZ5C;AAAA;AAAA;AAAA,uBAAAI;AAAA,EAAA,sBAAAC;AAAA,EAAA;AAAA;AAAA;;;ACEO,IAAM,QAAoB;AAAA,EAC/B,gBAAgB;AAAA,IACd,MAAM;AAAA,IACN,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA,kBAAkB;AAAA,IAChB,MAAM;AAAA,EACR;AAAA,EACA,sBAAsB;AAAA,IACpB,MAAM;AAAA,IACN,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA,4BAA4B;AAAA,IAC1B,MAAM;AAAA,EACR;AACF;;;ACpBO,IAAM,iBAAiB;AAAA,EAC5B,qBAAqB;AAAA,EACrB,mBAAmBC;AACrB;AAGO,IAAM,gBAAgB;AAAA,EAC3B,qBAAqB;AAAA,IACnB;AAAA,IACA;AAAA,EACF;AAAA,EACA,mBAAmB;AAAA,IACjB,UAA0BC;AAAA,IAC1B,SAAyBC;AAAA,IACzB;AAAA,EACF;AACF;","names":["examples_exports","env_exports","step_exports","env_exports","push","simulation","step_exports","pageView","getEvent","z","zodToSchema","z","SettingsSchema","z","MappingSchema","z","settings","zodToSchema","SettingsSchema","mapping","MappingSchema","mapping","settings","examples_exports","settings","mapping"]}
|
|
1
|
+
{"version":3,"sources":["../src/bigquery/examples/index.ts","../src/bigquery/examples/env.ts","../src/bigquery/__mocks__/@google-cloud/bigquery-storage.ts","../src/bigquery/examples/step.ts","../src/bigquery/eventToRow.ts","../src/pubsub/examples/index.ts","../src/pubsub/examples/env.ts","../src/pubsub/examples/step.ts","../src/bigquery/schemas/index.ts","../src/bigquery/schemas/settings.ts","../src/bigquery/schemas/mapping.ts","../src/pubsub/schemas/index.ts","../src/pubsub/schemas/settings.ts","../src/pubsub/schemas/mapping.ts","../src/pubsub/schemas/setup.ts","../src/schemas.ts","../src/hints.ts","../src/dev.ts"],"sourcesContent":["export * as env from './env';\nexport * as step from './step';\n","import type { Env, QueryClient, TableMetadataShape } from '../types';\nimport {\n managedwriter as mockManagedwriter,\n adapt as mockAdapt,\n} from '../__mocks__/@google-cloud/bigquery-storage';\n\n/**\n * Example environment configurations for GCP BigQuery destination\n *\n * These environments provide standardized mock structures for testing\n * and development without requiring actual BigQuery SDK dependencies.\n *\n * The Storage Write API mocks (WriterClient, JSONWriter, adapt) are\n * re-exported from the package-local __mocks__ folder so example/test\n * code shares a single source of truth with the jest auto-mock.\n */\n\n/**\n * Mock BigQuery query client: dataset and table provisioning calls resolve as\n * if both already exist.\n */\nfunction createMockBigQuery() {\n return class MockBigQuery implements QueryClient {\n calls: Array<{ method: string; args: unknown[] }>;\n options: unknown;\n\n constructor(options?: unknown) {\n this.options = options;\n this.calls = [];\n }\n\n dataset(datasetId: string) {\n this.calls.push({ method: 'dataset', args: [datasetId] });\n return this;\n }\n\n table(tableId: string) {\n this.calls.push({ method: 'table', args: [tableId] });\n return this;\n }\n\n async exists(): Promise<[boolean]> {\n this.calls.push({ method: 'exists', args: [] });\n return [true];\n }\n\n async create(options: unknown): Promise<void> {\n this.calls.push({ method: 'create', args: [options] });\n }\n\n async getMetadata(): Promise<[TableMetadataShape]> {\n this.calls.push({ method: 'getMetadata', args: [] });\n return [{}];\n }\n };\n}\n\n/**\n * Standard mock environment for push operations\n *\n * Use this for testing BigQuery Storage Write appends without connecting\n * to actual GCP infrastructure.\n */\nexport const push: Env = {\n get BigQuery() {\n return createMockBigQuery();\n },\n get WriterClient() {\n return mockManagedwriter.WriterClient;\n },\n get JSONWriter() {\n return mockManagedwriter.JSONWriter;\n },\n get adapt() {\n return mockAdapt;\n },\n};\n\n/**\n * Every row goes through the writer's `appendRows`; the writer is built from\n * `JSONWriter` in init, so the path continues on the constructed instance.\n * Constructors are not recorded: their arguments carry credentials.\n */\nexport const simulation = ['call:JSONWriter.appendRows'];\n","import { EventEmitter } from 'events';\n\nconst calls: Array<{ method: string; args: unknown[] }> = [];\n\ninterface MockRowError {\n index: number;\n code: number;\n message: string;\n}\n\nlet nextAppendRowErrors: MockRowError[] | null = null;\nlet nextAppendThrow: unknown = null;\nlet nextGetResultReject: unknown = null;\nlet nextAppendStatus: { code: number; message: string } | null = null;\nlet nextCreateStreamConnectionError: unknown = null;\n\n/**\n * Honest stand-in for the SDK's StreamConnection: a REAL Node EventEmitter so\n * `emit('error', …)` with no listener throws exactly like the real one (Node's\n * special-cased `'error'` event). `onConnectionError` mirrors the SDK surface:\n * it registers an `'error'` listener and returns an `{ off }` disposable.\n */\nclass MockStreamConnection extends EventEmitter {\n private readonly streamId: string;\n constructor(streamId: string) {\n super();\n this.streamId = streamId;\n }\n getStreamId(): string {\n return this.streamId;\n }\n onConnectionError(listener: (err: unknown) => void): { off: () => void } {\n calls.push({ method: 'onConnectionError', args: [] });\n this.on('error', listener);\n return {\n off: () => {\n this.off('error', listener);\n },\n };\n }\n /**\n * Test-only: literally `this.emit('error', err)` with NO internal\n * listener-count guard, so before a listener is attached this reproduces\n * Node's real \"throw if no 'error' listener\" behavior. A fake that silently\n * swallowed would mask the very crash this listener exists to contain.\n */\n __emitConnectionError(err: unknown): void {\n this.emit('error', err);\n }\n}\n\n// The most recently created connection, so tests can emit on it and assert the\n// listener was registered.\nlet lastConnection: MockStreamConnection | null = null;\n\n// Every connection ever created (this reset cycle), so tests can assert that a\n// concurrent re-open did not orphan a connection still carrying an 'error'\n// listener.\nconst allConnections: MockStreamConnection[] = [];\n\nclass MockJSONWriter {\n constructor(_args: { connection: unknown; protoDescriptor: unknown }) {\n calls.push({ method: 'JSONWriter.ctor', args: [_args] });\n }\n appendRows(rows: unknown[], offsetValue?: unknown) {\n calls.push({ method: 'appendRows', args: [rows, offsetValue] });\n const queuedThrow = nextAppendThrow;\n if (queuedThrow !== null) {\n nextAppendThrow = null;\n throw queuedThrow;\n }\n const queuedErrors = nextAppendRowErrors;\n nextAppendRowErrors = null;\n const queuedReject = nextGetResultReject;\n nextGetResultReject = null;\n const queuedStatus = nextAppendStatus;\n nextAppendStatus = null;\n return {\n getResult: async () => {\n // Models a gRPC deadline-exceeded (or any stream error): the append is\n // accepted but getResult() rejects when the stream's deadline fires.\n if (queuedReject !== null) throw queuedReject;\n // An error status the SDK does not retry resolves with `error` set\n // and no rowErrors.\n if (queuedStatus !== null)\n return {\n error: queuedStatus,\n writeStream: 'projects/p/datasets/d/tables/t/streams/_default',\n };\n return {\n appendResult: { offset: { value: '0' } },\n rowErrors: queuedErrors ?? [],\n writeStream: 'projects/p/datasets/d/tables/t/streams/_default',\n };\n },\n };\n }\n close(): void {\n calls.push({ method: 'JSONWriter.close', args: [] });\n }\n}\n\nclass MockWriterClient {\n constructor(args: {\n projectId?: string;\n keyFilename?: string;\n credentials?: unknown;\n scopes?: string | string[];\n }) {\n calls.push({ method: 'WriterClient.ctor', args: [args] });\n }\n async createStreamConnection(\n args: {\n destinationTable: string;\n streamId: string;\n },\n options?: unknown,\n ) {\n // Match the real SDK: callers must pass streamId=DefaultStream (not streamType)\n // for default-stream use. Passing streamType triggers a CreateWriteStream\n // call with type='DEFAULT', which BQ rejects as TYPE_UNSPECIFIED.\n if (args.streamId !== 'DEFAULT') {\n throw new Error(\n `mock createStreamConnection: expected streamId='DEFAULT', got ${JSON.stringify(args)}`,\n );\n }\n // args[1] captures the gax CallOptions (e.g. { timeout }) so tests can\n // assert the request deadline is forwarded to the appendRows stream.\n calls.push({ method: 'createStreamConnection', args: [args, options] });\n const queuedError = nextCreateStreamConnectionError;\n if (queuedError !== null) {\n nextCreateStreamConnectionError = null;\n throw queuedError;\n }\n const connection = new MockStreamConnection(\n `${args.destinationTable}/streams/_default`,\n );\n lastConnection = connection;\n allConnections.push(connection);\n return connection;\n }\n async getWriteStream(\n args: { streamId: string; view?: number },\n options?: unknown,\n ) {\n // args[1] captures the gax CallOptions so tests can assert the deadline\n // is forwarded to the unary schema fetch.\n calls.push({ method: 'getWriteStream', args: [args, options] });\n // Minimal tableSchema shape consumed by adapt.convertStorageSchemaToProto2Descriptor\n return {\n tableSchema: { fields: [] },\n };\n }\n close(): void {\n calls.push({ method: 'WriterClient.close', args: [] });\n }\n}\n\nconst adapt = {\n convertStorageSchemaToProto2Descriptor: (_schema: unknown, _root: string) => {\n calls.push({\n method: 'adapt.convertStorageSchemaToProto2Descriptor',\n args: [_schema, _root],\n });\n return { name: 'root', field: [] };\n },\n};\n\nconst managedwriter = {\n WriterClient: MockWriterClient,\n JSONWriter: MockJSONWriter,\n DefaultStream: 'DEFAULT',\n};\n\nconst protos = {\n google: {\n cloud: {\n bigquery: {\n storage: {\n v1: {\n WriteStreamView: {\n WRITE_STREAM_VIEW_UNSPECIFIED: 0,\n BASIC: 1,\n FULL: 2,\n },\n },\n },\n },\n },\n },\n};\n\n// Test-only helper. Not part of the real SDK.\nfunction __getMockCalls() {\n return calls;\n}\n\nfunction __resetMockCalls() {\n calls.length = 0;\n nextAppendRowErrors = null;\n nextAppendThrow = null;\n nextGetResultReject = null;\n nextAppendStatus = null;\n nextCreateStreamConnectionError = null;\n lastConnection = null;\n allConnections.length = 0;\n}\n\n/**\n * Test-only: the most recently created StreamConnection, so a test can emit an\n * out-of-band `'error'` on it (via `__emitConnectionError`) and assert the\n * destination attached a listener.\n */\nfunction __getLastConnection(): MockStreamConnection {\n if (!lastConnection) throw new Error('mock: no StreamConnection created yet');\n return lastConnection;\n}\n\n/**\n * Test-only: every StreamConnection created since the last reset, so a test can\n * assert that a concurrent re-open did not orphan a connection that still\n * carries an 'error' listener (a leak).\n */\nfunction __getAllConnections(): MockStreamConnection[] {\n return allConnections.slice();\n}\n\n/**\n * Test-only: queue rowErrors for the next appendRows().getResult() call.\n * Auto-resets after one use.\n */\nfunction __setNextAppendRowErrors(errors: MockRowError[]): void {\n nextAppendRowErrors = errors;\n}\n\n/**\n * Test-only: make the next appendRows() throw synchronously, simulating a\n * Storage Write API call failure. Auto-resets after one use.\n */\nfunction __setNextAppendThrow(err: unknown): void {\n nextAppendThrow = err;\n}\n\n/**\n * Test-only: make the next appendRows().getResult() reject, simulating a gRPC\n * deadline-exceeded (or any stream error) surfacing through the pending write.\n * Auto-resets after one use.\n */\nfunction __setNextGetResultReject(err: unknown): void {\n nextGetResultReject = err;\n}\n\n/**\n * Test-only: make the next appendRows().getResult() resolve with an error\n * status (a quota, a dropped table), as the SDK does for a status it does not\n * retry. Auto-resets after one use.\n */\nfunction __setNextAppendStatus(status: {\n code: number;\n message: string;\n}): void {\n nextAppendStatus = status;\n}\n\n/**\n * Test-only: queue an error for the next createStreamConnection() call so\n * tests can simulate openWriter failures (NotFound, INVALID_ARGUMENT, etc.).\n * Auto-resets after one use.\n */\nfunction __setNextOpenWriterError(err: unknown): void {\n nextCreateStreamConnectionError = err;\n}\n\nexport {\n managedwriter,\n adapt,\n protos,\n MockStreamConnection,\n __getMockCalls,\n __resetMockCalls,\n __getLastConnection,\n __getAllConnections,\n __setNextAppendRowErrors,\n __setNextAppendThrow,\n __setNextGetResultReject,\n __setNextAppendStatus,\n __setNextOpenWriterError,\n};\n","import type { Flow, WalkerOS } from '@walkeros/core';\nimport { getEvent } from '@walkeros/core';\nimport { eventToRow } from '../eventToRow';\n\n/**\n * Mirror of push.ts via eventToRow() -- produces a flat 15-column row\n * with nested object/array values JSON-stringified. Imported directly\n * from the runtime helper so the step examples stay in sync with what\n * push.ts actually emits to JSONWriter.appendRows.\n */\nfunction expectedRow(event: WalkerOS.Event) {\n return eventToRow(event);\n}\n\n/**\n * Page view -- one row appended through JSONWriter.appendRows([row]).\n * Captured as a single intent-level call: ['appendRows', [row]].\n */\nconst pageViewEvent = getEvent('page view', {\n timestamp: 1700001100,\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n source: { type: 'express', platform: 'server' },\n});\n\nexport const pageView: Flow.StepExample = {\n title: 'Page view',\n description:\n 'A page view is appended as one row through the BigQuery Storage Write API JSONWriter. Nested objects/arrays in data, source, etc. are JSON-stringified by eventToRow.',\n in: pageViewEvent,\n mapping: undefined,\n out: [['appendRows', [expectedRow(pageViewEvent)]]],\n};\n\n/**\n * Purchase -- nested array in data.items is JSON.stringified into the\n * data column of the appended row.\n */\nconst purchaseEvent = getEvent('order complete', {\n timestamp: 1700001101,\n data: {\n id: 'ORD-500',\n value: 199.99,\n items: [{ sku: 'SKU-1', qty: 2 }],\n },\n source: { type: 'express', platform: 'server' },\n});\n\nexport const purchase: Flow.StepExample = {\n title: 'Purchase',\n description:\n 'An order event is appended as a single row through JSONWriter.appendRows. The entire nested data object (including arrays like items) is JSON-stringified into the data column via eventToRow().',\n in: purchaseEvent,\n mapping: undefined,\n out: [['appendRows', [expectedRow(purchaseEvent)]]],\n};\n\n/** A silent rule appends no row. */\nexport const silentRule: Flow.StepExample = {\n public: false,\n description: 'A rule with silent: true appends no row.',\n in: getEvent('page view', { timestamp: 1700000000500 }),\n mapping: { silent: true },\n out: [],\n};\n\n/**\n * A failed append: the Storage Write call fails, so the row is not written\n * and the push fails, retryable, instead of counting as delivered. An append\n * the server answers with an error status (a quota, a dropped table) fails\n * the same way, retryable only for the statuses the SDK retries itself.\n */\nexport const appendFailed: Flow.StepExample = {\n public: false,\n description:\n 'A failed Storage Write append fails the push, retryable, instead of counting as delivered.',\n in: getEvent('page view', { timestamp: 1700001102 }),\n respond: { error: 'network' },\n out: [\n [\n 'appendRows',\n [expectedRow(getEvent('page view', { timestamp: 1700001102 }))],\n ],\n ],\n outcome: { status: 'failed', code: 'transport', retryable: true },\n};\n","import type { WalkerOS } from '@walkeros/core';\n\n/** Row shape passed to JSONWriter.appendRows. Values are JSON-serializable scalars or strings. */\nexport interface BigQueryRow {\n [key: string]: string | number | null;\n name: string;\n data: string | null;\n context: string | null;\n globals: string | null;\n custom: string | null;\n user: string | null;\n nested: string | null;\n consent: string | null;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n source: string | null;\n}\n\nfunction jsonOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'object') {\n if (Array.isArray(value) && value.length === 0) return null;\n if (!Array.isArray(value) && Object.keys(value).length === 0) return null;\n return JSON.stringify(value);\n }\n return JSON.stringify(value);\n}\n\n/** Convert a walkerOS Event v4 into a 15-column BigQuery row in canonical order.\n *\n * Note: BQ Storage Write API encodes TIMESTAMP fields as INT64 microseconds\n * since epoch (the SDK calls Long.fromString on the value). ISO strings fail\n * with \"interior hyphen\" because Long.fromString sees the date hyphens as\n * non-numeric. Pass microseconds directly.\n */\nexport function eventToRow(event: WalkerOS.Event): BigQueryRow {\n return {\n name: event.name,\n data: jsonOrNull(event.data),\n context: jsonOrNull(event.context),\n globals: jsonOrNull(event.globals),\n custom: jsonOrNull(event.custom),\n user: jsonOrNull(event.user),\n nested: jsonOrNull(event.nested),\n consent: jsonOrNull(event.consent),\n id: event.id,\n trigger: event.trigger,\n entity: event.entity,\n action: event.action,\n timestamp: new Date(event.timestamp).getTime() * 1000, // microseconds since epoch\n timing: event.timing,\n source: jsonOrNull(event.source),\n };\n}\n","export * as env from './env';\nexport * as step from './step';\n","import type {\n Env,\n PubSubPublisher,\n PublishMessage,\n TopicPublisher,\n} from '../types';\n\n/**\n * Example environment for the GCP Pub/Sub destination.\n *\n * `push` is the mock env simulate injects: `PubSub` builds a client whose\n * topics answer `publishMessage` locally, so nothing reaches GCP. Unit tests\n * still substitute the SDK module-wide via `jest.mock('@google-cloud/pubsub')`.\n */\n\nclass MockTopic implements TopicPublisher {\n constructor(public name: string) {}\n publishMessage(_message: PublishMessage): Promise<string> {\n return Promise.resolve('mock-message-id');\n }\n resumePublishing(_orderingKey: string): void {}\n}\n\nclass MockPubSub implements PubSubPublisher {\n constructor(public options?: object) {}\n topic(name: string): TopicPublisher {\n return new MockTopic(name);\n }\n close(): Promise<void> {\n return Promise.resolve();\n }\n}\n\nexport const push: Env = {\n PubSub: MockPubSub,\n};\n\n/** The publish carries the request; `args[0]` is the message. */\nexport const simulation = ['call:PubSub.topic.publishMessage'];\n","import type { Flow, WalkerOS } from '@walkeros/core';\nimport { getEvent } from '@walkeros/core';\n\n// Build-time version define. The upstream collector stamps source.release with\n// this on push, so the expected payload must mirror it rather than a literal,\n// else it breaks whenever the fixed version group is bumped (release).\ndeclare const __VERSION__: string;\n\n/**\n * Pub/Sub step examples. Each example's `out` is the array of recorded mock\n * calls produced by `push()`. The recording shape is:\n * ['topic', topicName, topicOptions] // implicit topic-handle creation\n * ['publishMessage', topicName, messageOptions]\n * ['resumePublishing', topicName, orderingKey] // only on publish failure\n */\n\n// Events reaching a server destination arrive already enriched by the upstream\n// collector, so they carry the run trace and per-run count. The collector\n// preserves these (stamp-if-absent), keeping the example deterministic.\nconst orderEvent = getEvent('order complete', {\n timestamp: 1700001100,\n data: { id: 'ORD-500', value: 199.99, currency: 'EUR' },\n user: { id: 'usr-789' },\n source: {\n type: 'express',\n platform: 'server',\n trace: '1a2b3c4d5e6f70819a2b3c4d5e6f7081',\n count: 1,\n },\n});\n\nconst pageEvent = getEvent('page view', {\n timestamp: 1700001101,\n data: { title: 'Documentation', url: 'https://example.com/docs' },\n source: {\n type: 'express',\n platform: 'server',\n trace: '9f8e7d6c5b4a39281706f5e4d3c2b1a0',\n count: 1,\n },\n});\n\nfunction expectedPayload(event: WalkerOS.Event): Buffer {\n // The harness pushes the event through an unconfigured collector, which stamps\n // source.release = { [name ?? platform ?? 'default']: __VERSION__ }. With no\n // collector name, the key is the event's platform. Mirror that here so the\n // expected message body matches the published (post-collector) event.\n const releaseKey = event.source.platform ?? 'default';\n const stamped = {\n ...event,\n source: { ...event.source, release: { [releaseKey]: __VERSION__ } },\n };\n return Buffer.from(JSON.stringify(stamped));\n}\n\n/**\n * Default publish, no mapping. Settings.topic = 'events'. The destination\n * constructs a topic handle inline with messageOrdering=false (no ordering\n * key resolved) and publishes the full event JSON as the message body.\n */\nexport const defaultPush: Flow.StepExample = {\n title: 'Default publish',\n description:\n 'An event is published to the configured Pub/Sub topic with the full JSON event as the message body and no ordering key.',\n in: orderEvent,\n out: [\n ['topic', 'events', { messageOrdering: false }],\n ['publishMessage', 'events', { data: expectedPayload(orderEvent) }],\n ],\n};\n\n/**\n * Per-rule topic override. Mapping carries `settings.topic = 'orders'`\n * which routes this rule to a dedicated topic.\n */\nexport const mappedTopic: Flow.StepExample = {\n title: 'Topic override',\n description:\n 'A mapping rule overrides the destination default topic so order events are published to a dedicated topic.',\n in: orderEvent,\n mapping: {\n settings: {\n topic: 'orders',\n },\n },\n out: [\n ['topic', 'orders', { messageOrdering: false }],\n ['publishMessage', 'orders', { data: expectedPayload(orderEvent) }],\n ],\n};\n\n/**\n * Per-rule ordering key resolved from the event. `mapping.orderingKey =\n * 'user.id'` is a Mapping.Value that resolves to the event's user.id. The\n * topic handle is constructed with messageOrdering=true and the publish\n * carries the resolved orderingKey.\n */\nexport const mappedOrderingKey: Flow.StepExample = {\n title: 'Ordering key from user',\n description:\n 'A mapping resolves the ordering key from event.user.id, enabling per-user ordering for this publish.',\n in: orderEvent,\n mapping: {\n settings: {\n orderingKey: 'user.id',\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: true }],\n [\n 'publishMessage',\n 'events',\n {\n data: expectedPayload(orderEvent),\n orderingKey: 'usr-789',\n },\n ],\n ],\n};\n\n/**\n * Per-rule attributes. `mapping.attributes = { entity: 'entity', action:\n * 'action' }` is a Mapping.Map resolved per event. Each value is a path\n * resolved against the event.\n */\nexport const mappedAttributes: Flow.StepExample = {\n title: 'Mapped attributes',\n description:\n 'A mapping resolves a per-event attribute map, here exposing entity and action as Pub/Sub attributes for routing in subscribers.',\n in: orderEvent,\n mapping: {\n settings: {\n attributes: {\n entity: 'entity',\n action: 'action',\n },\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: false }],\n [\n 'publishMessage',\n 'events',\n {\n data: expectedPayload(orderEvent),\n attributes: { entity: 'order', action: 'complete' },\n },\n ],\n ],\n};\n\n/**\n * Mapped data. `mapping.data` rewrites the publish body. The rewritten\n * object replaces the event as the message data.\n */\nexport const mappedData: Flow.StepExample = {\n title: 'Mapped payload',\n description:\n 'A data mapping transforms the event payload before publish. The rewritten object becomes the Pub/Sub message body.',\n in: orderEvent,\n mapping: {\n data: {\n map: {\n order_id: 'data.id',\n revenue: 'data.value',\n currency: 'data.currency',\n },\n },\n },\n out: [\n ['topic', 'events', { messageOrdering: false }],\n [\n 'publishMessage',\n 'events',\n {\n // Mapped-data publish: the body is the mapping result (no event\n // envelope, so no source.release), emitted verbatim.\n data: Buffer.from(\n JSON.stringify({\n order_id: 'ORD-500',\n revenue: 199.99,\n currency: 'EUR',\n }),\n ),\n },\n ],\n ],\n};\n\n/**\n * Page view, no rule. Verifies free-form publish on a non-ordered topic\n * for an event with no special mapping.\n */\nexport const pageView: Flow.StepExample = {\n title: 'Page view',\n description:\n 'A page view is published to the default topic with no ordering key, demonstrating the simplest publish path.',\n in: pageEvent,\n out: [\n ['topic', 'events', { messageOrdering: false }],\n ['publishMessage', 'events', { data: expectedPayload(pageEvent) }],\n ],\n};\n\n/** A silent rule publishes no message. */\nexport const silentRule: Flow.StepExample = {\n public: false,\n description: 'A rule with silent: true publishes no message.',\n in: getEvent('page view', { timestamp: 1700000000500 }),\n mapping: { silent: true },\n out: [],\n};\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z\n .object({\n client: z\n .any()\n .describe(\n 'Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n datasetId: z\n .string()\n .min(1)\n .default('walkerOS')\n .describe(\n 'BigQuery dataset ID where events will be stored (like walker_events)',\n ),\n tableId: z\n .string()\n .min(1)\n .default('events')\n .describe('BigQuery table ID for event storage (like events)'),\n location: z\n .string()\n .default('EU')\n .describe('Geographic location for the BigQuery dataset (like US)'),\n bigquery: z\n .any()\n .describe(\n 'Additional BigQuery client configuration options (like { keyFilename: \"path/to/key.json\" })',\n )\n .optional(),\n })\n .strict();\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP BigQuery Mapping Schema\n * BigQuery has no event-level mapping configuration\n */\nexport const MappingSchema = z.object({});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\nimport { SetupSchema } from './setup';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\nexport { SetupSchema, type Setup } from './setup';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\nexport const setup = zodToSchema(SetupSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z\n .object({\n client: z\n .any()\n .describe(\n 'Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n topic: z\n .string()\n .min(1)\n .describe(\n 'Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK.',\n ),\n credentials: z\n .any()\n .describe(\n 'Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)',\n )\n .optional(),\n apiEndpoint: z\n .string()\n .describe(\n 'Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Mapping value resolved per-event. Truthy enables per-key ordering for the publish.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Default per-event attribute map merged into every published message. Mapping.Map shape.',\n )\n .optional(),\n })\n .strict();\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Mapping Schema\n *\n * Per-rule overrides for topic, orderingKey, and attributes.\n */\nexport const MappingSchema = z.object({\n topic: z\n .string()\n .describe(\n 'Per-rule topic override. Falls back to settings.topic if absent.',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Per-rule attribute Mapping.Map merged on top of settings.attributes.',\n )\n .optional(),\n});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Setup Schema\n *\n * Provisioning options for `walkeros setup destination.<id>`. Idempotent topic\n * creation. Subscription provisioning is owned by the source side.\n */\nexport const SetupSchema = z.object({\n messageStoragePolicy: z\n .object({\n allowedPersistenceRegions: z\n .array(z.string())\n .describe(\n 'Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).',\n ),\n })\n .describe('Topic-level message storage policy.')\n .optional(),\n messageRetentionDuration: z\n .object({\n seconds: z\n .number()\n .describe('Retention window in seconds. Default: project default.'),\n })\n .describe('Topic-level retention configuration.')\n .optional(),\n kmsKeyName: z\n .string()\n .describe('Customer-managed encryption key (CMEK) resource name. Optional.')\n .optional(),\n labels: z\n .record(z.string(), z.string())\n .describe('Topic labels for organization and billing.')\n .optional(),\n});\n\nexport type Setup = z.infer<typeof SetupSchema>;\n","// Browser-safe schema-only exports\n// This file exports ONLY schemas without any Node.js dependencies\nexport { settings, mapping } from './bigquery/schemas';\nexport {\n settings as pubsubSettings,\n mapping as pubsubMapping,\n setup as pubsubSetup,\n} from './pubsub/schemas';\n","import type { Hint } from '@walkeros/core';\n\nexport const hints: Hint.Hints = {\n 'auth-methods': {\n text: 'Supports three auth methods: SA key file via bigquery options ({ bigquery: { keyFilename: \"./sa.json\" } }), Application Default Credentials (automatic on GCP infrastructure — just provide projectId), or a pre-configured BigQuery client instance (client option). See settings schema for all options.',\n code: [\n {\n lang: 'json',\n code: '{ \"settings\": { \"projectId\": \"my-project\", \"bigquery\": { \"keyFilename\": \"./sa.json\" } } }',\n },\n {\n lang: 'json',\n code: '{ \"settings\": { \"projectId\": \"my-project\" } }',\n },\n ],\n },\n 'storage-format': {\n text: 'All events are stored in a single table. Scalar fields (strings, numbers, booleans) are stored as-is. Nested objects and arrays are JSON-stringified automatically. Defaults: dataset \"walkeros\", table \"events\", location \"EU\" — all overridable via settings.',\n },\n 'query-json-columns': {\n text: 'Nested event fields (data, context, globals, user) are stored as JSON strings. Use BigQuery JSON_EXTRACT_SCALAR to query them. Field paths follow the walkerOS event structure.',\n code: [\n {\n lang: 'sql',\n code: \"SELECT JSON_EXTRACT_SCALAR(data, '$.value') AS value FROM `project.walkeros.events` WHERE entity = 'order'\",\n },\n ],\n },\n 'troubleshoot-empty-table': {\n text: \"Events not appearing? Common causes: projectId doesn't match GCP project, dataset doesn't exist yet (create via BigQuery console or bq CLI before first push), or SA key lacks bigquery.dataEditor role. The destination validates client/datasetId/tableId at push time but GCP permission errors surface from the BigQuery SDK.\",\n },\n};\n","import * as bigqueryExamplesNs from './bigquery/examples';\nimport * as pubsubExamplesNs from './pubsub/examples';\nimport * as bigquerySchemasNs from './bigquery/schemas';\nimport * as pubsubSchemasNs from './pubsub/schemas';\n\nexport * as schemas from './schemas';\nexport * as examples from './bigquery/examples';\nexport * as pubsubExamples from './pubsub/examples';\nexport { hints } from './hints';\n\n/** Dev examples per export, keyed by the export names in package.json. */\nexport const exportExamples = {\n destinationBigQuery: bigqueryExamplesNs,\n destinationPubSub: pubsubExamplesNs,\n};\n\n/** Schemas per export, keyed by the export names in package.json. */\nexport const exportSchemas = {\n destinationBigQuery: {\n settings: bigquerySchemasNs.settings,\n mapping: bigquerySchemasNs.mapping,\n },\n destinationPubSub: {\n settings: pubsubSchemasNs.settings,\n mapping: pubsubSchemasNs.mapping,\n setup: pubsubSchemasNs.setup,\n },\n};\n"],"mappings":";;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,oBAAoB;AAE7B,IAAM,QAAoD,CAAC;AAQ3D,IAAI,sBAA6C;AACjD,IAAI,kBAA2B;AAC/B,IAAI,sBAA+B;AACnC,IAAI,mBAA6D;AACjE,IAAI,kCAA2C;AAQ/C,IAAM,uBAAN,cAAmC,aAAa;AAAA,EAC7B;AAAA,EACjB,YAAY,UAAkB;AAC5B,UAAM;AACN,SAAK,WAAW;AAAA,EAClB;AAAA,EACA,cAAsB;AACpB,WAAO,KAAK;AAAA,EACd;AAAA,EACA,kBAAkB,UAAuD;AACvE,UAAM,KAAK,EAAE,QAAQ,qBAAqB,MAAM,CAAC,EAAE,CAAC;AACpD,SAAK,GAAG,SAAS,QAAQ;AACzB,WAAO;AAAA,MACL,KAAK,MAAM;AACT,aAAK,IAAI,SAAS,QAAQ;AAAA,MAC5B;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,sBAAsB,KAAoB;AACxC,SAAK,KAAK,SAAS,GAAG;AAAA,EACxB;AACF;AAIA,IAAI,iBAA8C;AAKlD,IAAM,iBAAyC,CAAC;AAEhD,IAAM,iBAAN,MAAqB;AAAA,EACnB,YAAY,OAA0D;AACpE,UAAM,KAAK,EAAE,QAAQ,mBAAmB,MAAM,CAAC,KAAK,EAAE,CAAC;AAAA,EACzD;AAAA,EACA,WAAW,MAAiB,aAAuB;AACjD,UAAM,KAAK,EAAE,Q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AA,uBAAAI;AAAA,EAAA,sBAAAC;AAAA,EAAA;AAAA;AAAA;;;ACEO,IAAM,QAAoB;AAAA,EAC/B,gBAAgB;AAAA,IACd,MAAM;AAAA,IACN,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA,kBAAkB;AAAA,IAChB,MAAM;AAAA,EACR;AAAA,EACA,sBAAsB;AAAA,IACpB,MAAM;AAAA,IACN,MAAM;AAAA,MACJ;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA,4BAA4B;AAAA,IAC1B,MAAM;AAAA,EACR;AACF;;;ACpBO,IAAM,iBAAiB;AAAA,EAC5B,qBAAqB;AAAA,EACrB,mBAAmBC;AACrB;AAGO,IAAM,gBAAgB;AAAA,EAC3B,qBAAqB;AAAA,IACnB;AAAA,IACA;AAAA,EACF;AAAA,EACA,mBAAmB;AAAA,IACjB,UAA0BC;AAAA,IAC1B,SAAyBC;AAAA,IACzB;AAAA,EACF;AACF;","names":["examples_exports","env_exports","step_exports","env_exports","push","simulation","step_exports","pageView","silentRule","getEvent","z","zodToSchema","z","SettingsSchema","z","MappingSchema","z","settings","zodToSchema","SettingsSchema","mapping","MappingSchema","mapping","settings","examples_exports","settings","mapping"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -22,7 +22,7 @@ interface WriteConnection {
|
|
|
22
22
|
onConnectionError(listener: (err: unknown) => void): ConnectionListener;
|
|
23
23
|
}
|
|
24
24
|
/** The fields of an append response that push and pushBatch read. */
|
|
25
|
-
type AppendOutcome = Pick<AppendResponse, 'rowErrors' | 'appendResult'>;
|
|
25
|
+
type AppendOutcome = Pick<AppendResponse, 'rowErrors' | 'appendResult' | 'error'>;
|
|
26
26
|
/** The row writer surface push and pushBatch use. */
|
|
27
27
|
interface RowWriter {
|
|
28
28
|
appendRows(rows: RowList): {
|
package/dist/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ interface WriteConnection {
|
|
|
22
22
|
onConnectionError(listener: (err: unknown) => void): ConnectionListener;
|
|
23
23
|
}
|
|
24
24
|
/** The fields of an append response that push and pushBatch read. */
|
|
25
|
-
type AppendOutcome = Pick<AppendResponse, 'rowErrors' | 'appendResult'>;
|
|
25
|
+
type AppendOutcome = Pick<AppendResponse, 'rowErrors' | 'appendResult' | 'error'>;
|
|
26
26
|
/** The row writer surface push and pushBatch use. */
|
|
27
27
|
interface RowWriter {
|
|
28
28
|
appendRows(rows: RowList): {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var mod,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,index_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(index_exports,{DestinationBigQuery:()=>types_exports,DestinationPubSub:()=>types_exports2,default:()=>destinationBigQuery,destinationBigQuery:()=>destinationBigQuery,destinationPubSub:()=>destinationPubSub}),module.exports=(mod=index_exports,((to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to})(__defProp({},"__esModule",{value:!0}),mod));var import_bigquery=require("@google-cloud/bigquery"),import_core=require("@walkeros/core"),import_pubsub=require("@google-cloud/pubsub");function resolveCredentials(partialConfig,logger){if(void 0!==partialConfig.credentials)return partialConfig.credentials;const fromSettings=partialConfig.settings?.credentials;return void 0!==fromSettings?(logger.warn("settings.credentials is deprecated; use config.credentials"),fromSettings):void 0}function parseCredentials(raw,logger){if(void 0!==raw){if("string"==typeof raw)try{const parsed=JSON.parse(raw);return function(value){if(!(0,import_core.isObject)(value))return!1;const candidate=value;return"string"==typeof candidate.client_email&&"string"==typeof candidate.private_key}(parsed)?parsed:void logger.throw("Invalid credentials JSON")}catch{return void logger.throw("Invalid credentials JSON")}return raw}}var import_core2=require("@walkeros/core");function jsonOrNull(value){return null==value?null:"object"==typeof value?Array.isArray(value)&&0===value.length?null:Array.isArray(value)||0!==Object.keys(value).length?JSON.stringify(value):null:JSON.stringify(value)}function eventToRow(event){return{name:event.name,data:jsonOrNull(event.data),context:jsonOrNull(event.context),globals:jsonOrNull(event.globals),custom:jsonOrNull(event.custom),user:jsonOrNull(event.user),nested:jsonOrNull(event.nested),consent:jsonOrNull(event.consent),id:event.id,trigger:event.trigger,entity:event.entity,action:event.action,timestamp:1e3*new Date(event.timestamp).getTime(),timing:event.timing,source:jsonOrNull(event.source)}}var import_bigquery_storage=require("@google-cloud/bigquery-storage");function openWriter(args,logger){const{env:env}=args;if(!env?.WriterClient){return openWith({WriterClient:import_bigquery_storage.managedwriter.WriterClient,JSONWriter:env?.JSONWriter??import_bigquery_storage.managedwriter.JSONWriter,adapt:env?.adapt??import_bigquery_storage.adapt},args,logger)}return openWith({WriterClient:env.WriterClient,JSONWriter:env.JSONWriter??MissingJSONWriter,adapt:env.adapt??import_bigquery_storage.adapt},args,logger)}var MISSING_JSON_WRITER="BigQuery env: an injected WriterClient needs an injected JSONWriter; its connection cannot feed the SDK writer.",MissingJSONWriter=class{constructor(){throw new Error(MISSING_JSON_WRITER)}appendRows(){throw new Error(MISSING_JSON_WRITER)}close(){}};async function openWith({WriterClient:WriterClient,JSONWriter:JSONWriter,adapt:adaptFn},args,logger){const{projectId:projectId,datasetId:datasetId,tableId:tableId,credentials:credentials,bigquery:bigquery,timeout:timeout,onConnectionError:onConnectionError}=args,destinationTable=`projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;logger.debug("Opening BigQuery Storage Write API writer",{destinationTable:destinationTable});const callOptions=void 0===timeout?void 0:{timeout:timeout},writeClient=new WriterClient({projectId:projectId,...bigquery,...void 0!==credentials?{credentials:credentials}:{}});let connectionErrorListener,connection;try{connection=await writeClient.createStreamConnection({destinationTable:destinationTable,streamId:import_bigquery_storage.managedwriter.DefaultStream}),onConnectionError&&(connectionErrorListener=connection.onConnectionError(err=>{onConnectionError(err)}));const streamId=connection.getStreamId(),writeStream=await writeClient.getWriteStream({streamId:streamId,view:import_bigquery_storage.protos.google.cloud.bigquery.storage.v1.WriteStreamView.FULL},callOptions);if(!writeStream.tableSchema)throw new Error(`BigQuery write stream ${streamId} returned no tableSchema; cannot build proto descriptor`);const protoDescriptor=adaptFn.convertStorageSchemaToProto2Descriptor(writeStream.tableSchema,"root");return{writeClient:writeClient,writer:new JSONWriter({connection:connection,protoDescriptor:protoDescriptor}),connection:connection,connectionErrorListener:connectionErrorListener}}catch(err){throw closeWriter({writeClient:writeClient,connectionErrorListener:connectionErrorListener},logger),err}}function ensureWriter(settings,logger){if(!settings.writerBroken)return Promise.resolve();if(settings.reopenInFlight)return settings.reopenInFlight;const lastError=settings.lastStreamError;logger.info("BigQuery writer broken; attempting one re-open before failing",{error:lastError?lastError.message:"unknown stream error"});const reopen=settings.reopenWriter;if(!reopen)return Promise.reject(new Error("BigQuery writer is broken and no re-open hook is configured: "+(lastError?lastError.message:"unknown stream error")));const inFlight=(async()=>{try{closeWriter({writer:settings.writer,writeClient:settings.writeClient,connectionErrorListener:settings.connectionErrorListener},logger);const handles=await reopen();settings.writeClient=handles.writeClient,settings.writer=handles.writer,settings.connection=handles.connection,settings.connectionErrorListener=handles.connectionErrorListener,settings.writerBroken=!1,settings.lastStreamError=void 0,logger.info("BigQuery writer re-opened after a stream error")}finally{settings.reopenInFlight=void 0}})();return settings.reopenInFlight=inFlight,inFlight}function closeWriter(handles,logger){try{handles.connectionErrorListener?.off()}catch(err){logger.warn("connection error listener removal failed",{error:String(err)})}try{handles.writer?.close()}catch(err){logger.warn("writer.close failed",{error:String(err)})}try{handles.writeClient?.close()}catch(err){logger.warn("writeClient.close failed",{error:String(err)})}}var import_core3=require("@walkeros/core"),import_core4=require("@walkeros/core"),DEFAULT_SETUP={location:"EU",storageBillingModel:"PHYSICAL",partitioning:{type:"DAY",field:"timestamp"},clustering:{fields:["name","entity","action"]},schema:[{name:"name",type:"STRING",mode:"REQUIRED"},{name:"data",type:"JSON",mode:"NULLABLE"},{name:"context",type:"JSON",mode:"NULLABLE"},{name:"globals",type:"JSON",mode:"NULLABLE"},{name:"custom",type:"JSON",mode:"NULLABLE"},{name:"user",type:"JSON",mode:"NULLABLE"},{name:"nested",type:"JSON",mode:"NULLABLE"},{name:"consent",type:"JSON",mode:"NULLABLE"},{name:"id",type:"STRING",mode:"NULLABLE"},{name:"trigger",type:"STRING",mode:"NULLABLE"},{name:"entity",type:"STRING",mode:"NULLABLE"},{name:"action",type:"STRING",mode:"NULLABLE"},{name:"timestamp",type:"TIMESTAMP",mode:"NULLABLE"},{name:"timing",type:"FLOAT64",mode:"NULLABLE"},{name:"source",type:"JSON",mode:"NULLABLE"}]};function isAlreadyExists(err){return function(err){return"object"==typeof err&&null!==err&&("code"in err&&"number"==typeof err.code)}(err)&&409===err.code}var types_exports={},destinationBigQuery={type:"gcp-bigquery",config:{},setup:async function(ctx){const{config:config,logger:logger}=ctx,merged=(0,import_core4.resolveSetup)(config.setup,DEFAULT_SETUP);if(!merged)return void logger.debug("setup: skipped (config.setup is false or unset)");const options={location:merged.location??DEFAULT_SETUP.location,storageBillingModel:merged.storageBillingModel??DEFAULT_SETUP.storageBillingModel,partitioning:merged.partitioning??DEFAULT_SETUP.partitioning,clustering:merged.clustering??DEFAULT_SETUP.clustering,schema:merged.schema??DEFAULT_SETUP.schema};if(!config.settings)return void logger.throw("setup: settings missing");const{client:client,datasetId:datasetId,tableId:tableId}=config.settings;if(!client)return void logger.throw("setup: BigQuery client is missing");if(!datasetId)return void logger.throw("setup: datasetId is missing");if(!tableId)return void logger.throw("setup: tableId is missing");const dataset=client.dataset(datasetId);let datasetCreated=!1;const[datasetExists]=await dataset.exists();if(datasetExists)logger.debug("setup: dataset exists",{datasetId:datasetId});else try{await dataset.create({location:options.location,storageBillingModel:options.storageBillingModel}),datasetCreated=!0,logger.info("setup: dataset created",{datasetId:datasetId,location:options.location,storageBillingModel:options.storageBillingModel})}catch(err){if(!isAlreadyExists(err))throw err;logger.debug("setup: dataset already exists (race)",{datasetId:datasetId})}const table=dataset.table(tableId);let tableCreated=!1;const[tableExists]=await table.exists();if(tableExists)logger.debug("setup: table exists",{datasetId:datasetId,tableId:tableId}),await async function(table,options,logger){let metadata;try{const[meta]=await table.getMetadata();metadata=meta??{}}catch(err){return void logger.debug("setup: drift check failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(v=metadata.timePartitioning,"object"==typeof v&&null!==v){const actual=metadata.timePartitioning,declared=options.partitioning;actual.type===declared.type&&actual.field===declared.field||logger.warn("setup.drift",{field:"timePartitioning",declared:declared,actual:actual})}var v;if(function(v){return"object"==typeof v&&null!==v}(metadata.clustering)){const actualFields=metadata.clustering.fields??[],declaredFields=options.clustering.fields;(actualFields.length!==declaredFields.length||actualFields.some((f,i)=>f!==declaredFields[i]))&&logger.warn("setup.drift",{field:"clustering",declared:{fields:declaredFields},actual:{fields:actualFields}})}if(function(v){return"object"==typeof v&&null!==v}(metadata.schema)){const actualFields=metadata.schema.fields??[],declaredFields=options.schema;(actualFields.length!==declaredFields.length||declaredFields.some((d,i)=>{const a=actualFields[i];return!a||a.name!==d.name||a.type!==d.type||a.mode!==d.mode}))&&logger.warn("setup.drift",{field:"schema",declared:declaredFields.map(f=>({name:f.name,type:f.type,mode:f.mode})),actual:actualFields.map(f=>({name:f.name,type:f.type,mode:f.mode}))})}}(table,options,logger);else try{await table.create({schema:{fields:options.schema},timePartitioning:{type:options.partitioning.type,field:options.partitioning.field},clustering:{fields:options.clustering.fields}}),tableCreated=!0,logger.info("setup: table created",{datasetId:datasetId,tableId:tableId,partitioning:options.partitioning,clustering:options.clustering})}catch(err){if(!isAlreadyExists(err))throw err;logger.debug("setup: table already exists (race)",{tableId:tableId})}return{datasetCreated:datasetCreated,tableCreated:tableCreated}},async init({config:partialConfig,env:env,logger:logger,id:id,reportError:reportError}){const config=function(partialConfig={},env,logger){const settings=partialConfig.settings||{},{projectId:projectId,bigquery:bigquery}=settings;let{client:client,location:location,datasetId:datasetId,tableId:tableId}=settings;projectId||logger.throw("Config settings projectId missing"),location=location||"EU",datasetId=datasetId||"walkerOS",tableId=tableId||"events";const options={...bigquery||{}};options.projectId=projectId;const parsed=parseCredentials(partialConfig.credentials,logger),credentials=void 0!==parsed&&"string"!=typeof parsed?parsed:void 0;void 0!==credentials&&(options.credentials=credentials);const BigQueryClass=env?.BigQuery||import_bigquery.BigQuery;client=client||new BigQueryClass(options);const settingsConfig={...settings,client:client,projectId:projectId,location:location,datasetId:datasetId,tableId:tableId,...void 0!==credentials?{credentials:credentials}:{}};return{...partialConfig,settings:settingsConfig}}(partialConfig,env,logger),timeout=config.timeout&&config.timeout>0?config.timeout:1e4,{settings:settings}=config,onConnectionError=err=>{settings.writerBroken=!0,settings.lastStreamError=err instanceof Error?err:new Error(String(err)),reportError?.(err)};settings.reopenWriter=()=>openWriter({projectId:settings.projectId,datasetId:settings.datasetId,tableId:settings.tableId,credentials:settings.credentials,bigquery:settings.bigquery,timeout:timeout,onConnectionError:onConnectionError,env:env},logger);try{const{writer:writer,writeClient:writeClient,connection:connection,connectionErrorListener:connectionErrorListener}=await openWriter({projectId:settings.projectId,datasetId:settings.datasetId,tableId:settings.tableId,credentials:settings.credentials,bigquery:settings.bigquery,timeout:timeout,onConnectionError:onConnectionError,env:env},logger);settings.writer=writer,settings.writeClient=writeClient,settings.connection=connection,settings.connectionErrorListener=connectionErrorListener}catch(err){const message=err instanceof Error?err.message:String(err);if(function(err){if("object"!=typeof err||null===err)return!1;if(!("code"in err))return!1;const obj=err;return 5===obj.code||404===obj.code}(err)){const target=`${config.settings.datasetId}.${config.settings.tableId}`,project=config.settings.projectId;logger.error(`BigQuery dataset or table not found: project="${project}", target="${target}". Run "walkeros setup destination.${id}" to create them.`,{project:project,target:target,error:message})}else logger.error("BigQuery init failed",{error:message});throw err}return config},push:async(event,context)=>await async function(event,{config:config,rule:_rule,data:data,logger:logger}){const settings=config.settings;if(!settings)return logger.throw("settings missing, init() not run");if(!settings.writer)return logger.throw("writer is missing, init() not run");settings.writerBroken&&await ensureWriter(settings,logger);const{writer:writer,datasetId:datasetId,tableId:tableId}=settings;if(!writer)return logger.throw("writer is missing, init() not run");if(!datasetId)return logger.throw("datasetId is missing");if(!tableId)return logger.throw("tableId is missing");const rows=[(0,import_core2.isObject)(data)?data:eventToRow(event)];let result;logger.debug("Calling BigQuery Storage Write API",{dataset:datasetId,table:tableId,rowCount:rows.length});try{const pending=writer.appendRows(rows);result=await pending.getResult()}catch(err){throw logger.error("BigQuery row append threw",{error:err instanceof Error?err.message:String(err)}),err}if(result.rowErrors&&result.rowErrors.length>0){const first=result.rowErrors[0];return logger.throw(`BigQuery row append failed: code=${first.code} message=${first.message}`)}logger.debug("BigQuery Storage Write API response",{ok:!0,offset:result.appendResult?.offset?.value})}(event,context),pushBatch:async(batch,{config:config,logger:logger})=>{const settings=config.settings;if(!settings)return logger.throw("settings missing, init() not run");if(!settings.writer)return logger.throw("writer is missing, init() not run");settings.writerBroken&&await ensureWriter(settings,logger);const{writer:writer,datasetId:datasetId,tableId:tableId}=settings;if(!writer)return logger.throw("writer is missing, init() not run");if(!datasetId)return logger.throw("datasetId is missing");if(!tableId)return logger.throw("tableId is missing");const rows=batch.entries.map(e=>(0,import_core3.isObject)(e.data)?e.data:eventToRow(e.event));if(0!==rows.length)try{logger.debug("Calling BigQuery Storage Write API (batch)",{dataset:datasetId,table:tableId,rowCount:rows.length});const pending=writer.appendRows(rows),result=await pending.getResult();if(result.rowErrors&&result.rowErrors.length>0){const failed=result.rowErrors.length;logger.info("BigQuery batch had partial failures",{ok:rows.length-failed,failed:failed,rowCount:rows.length});for(const re of result.rowErrors)logger.error("BigQuery row append failed",{index:re.index,code:re.code,message:re.message});return{failed:result.rowErrors.map(re=>({index:Number(re.index),error:Object.assign(new Error(re.message??"BigQuery row error"),{code:re.code})}))}}logger.debug("BigQuery batch append ok",{ok:rows.length,failed:0,offset:result.appendResult?.offset?.value})}catch(err){throw logger.error("BigQuery batch append threw",{error:err instanceof Error?err.message:String(err)}),err}},async destroy({config:config,logger:logger}){config.settings&&closeWriter({writer:config.settings.writer,writeClient:config.settings.writeClient,connectionErrorListener:config.settings.connectionErrorListener},logger)}};var import_core5=require("@walkeros/core");function hasNumericCode(err){if("object"!=typeof err||null===err)return!1;if(!("code"in err))return!1;return"number"==typeof err.code}var push2=async function(event,{config:config,rule:rule,data:data,collector:collector,logger:logger,id:id}){const settings=config.settings;if(!function(value){if("object"!=typeof value||null===value)return!1;const candidate=value;return void 0!==candidate.client&&"string"==typeof candidate.projectId&&candidate.projectId.length>0&&"string"==typeof candidate.topic&&candidate.topic.length>0}(settings))return logger.throw("settings missing or incomplete, init() not run");const{client:client,projectId:projectId,topic:defaultTopic}=settings,ruleSettings=(value=rule?.settings,"object"==typeof value&&null!==value?rule.settings:{});var value;const topicName="string"==typeof ruleSettings.topic&&ruleSettings.topic.length>0?ruleSettings.topic:defaultTopic,orderingValue=void 0!==ruleSettings.orderingKey?ruleSettings.orderingKey:settings.orderingKey;let orderingKey;if(void 0!==orderingValue){const resolved=await(0,import_core5.getMappingValue)(event,orderingValue,{collector:collector});"string"==typeof resolved&&resolved.length>0?orderingKey=resolved:null!=resolved&&(orderingKey=String(resolved))}const topicHandle=client.topic(topicName,{messageOrdering:Boolean(orderingKey)}),body=(0,import_core5.isObject)(data)&&Object.keys(data).length>0?data:event,payload=Buffer.from(JSON.stringify(body)),baseAttrs=settings.attributes,ruleAttrs=ruleSettings.attributes,attributes=await async function(event,base,override,collector){const result={};let touched=!1;if(base)for(const[key,value]of Object.entries(base)){const resolved=await(0,import_core5.getMappingValue)(event,value,{collector:collector});"string"==typeof resolved?(result[key]=resolved,touched=!0):null!=resolved&&(result[key]=String(resolved),touched=!0)}if(override)for(const[key,value]of Object.entries(override)){const resolved=await(0,import_core5.getMappingValue)(event,value,{collector:collector});"string"==typeof resolved?(result[key]=resolved,touched=!0):null!=resolved&&(result[key]=String(resolved),touched=!0)}return touched?result:void 0}(event,baseAttrs,ruleAttrs,collector),message={data:payload};attributes&&function(value){if(!(0,import_core5.isObject)(value))return!1;const candidate=value;for(const key of Object.keys(candidate))if("string"!=typeof candidate[key])return!1;return!0}(attributes)&&(message.attributes=attributes),orderingKey&&(message.orderingKey=orderingKey),logger.debug("Pub/Sub publish",{topic:topicName,projectId:projectId,orderingKey:orderingKey,event:event.name});try{await topicHandle.publishMessage(message)}catch(err){if(orderingKey)try{topicHandle.resumePublishing(orderingKey)}catch(resumeErr){logger.debug("Pub/Sub resumePublishing failed",{orderingKey:orderingKey,error:resumeErr instanceof Error?resumeErr.message:String(resumeErr)})}throw!function(err){return hasNumericCode(err)&&(5===err.code||404===err.code)}(err)?!function(err){return hasNumericCode(err)&&(7===err.code||16===err.code||403===err.code||401===err.code)}(err)?logger.error("Pub/Sub publish failed",{topic:topicName,projectId:projectId,event:event.name,error:err instanceof Error?err.message:String(err)}):logger.error(`Pub/Sub publish denied for topic "${topicName}". Grant the runtime service account roles/pubsub.publisher on this topic.`,{topic:topicName,projectId:projectId,error:err instanceof Error?err.message:String(err)}):logger.error(`Pub/Sub topic "${topicName}" not found in project "${projectId}". Run "walkeros setup destination.${id}" to create it.`,{topic:topicName,projectId:projectId,error:err instanceof Error?err.message:String(err)}),err}},import_core6=require("@walkeros/core"),import_pubsub2=require("@google-cloud/pubsub"),DEFAULT_SETUP2={messageStoragePolicy:{allowedPersistenceRegions:["europe-west1","europe-west3","europe-west4"]}};async function safeClose(client,logger){try{await client.close()}catch(err){logger.debug("setup: client.close failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}var types_exports2={},destinationPubSub={type:"gcp-pubsub",config:{},setup:async function(ctx){const{config:config,logger:logger}=ctx,merged=(0,import_core6.resolveSetup)(config.setup,DEFAULT_SETUP2);if(!merged)return void logger.debug("setup: skipped (config.setup is false or unset)");const settings=config.settings;if(!settings)return void logger.throw("setup: settings missing");const projectId="string"==typeof settings.projectId?settings.projectId:"",topicName="string"==typeof settings.topic?settings.topic:"";if(!projectId)return void logger.throw("setup: projectId is missing");if(!topicName)return void logger.throw("setup: topic is missing");let createdClient=!1,client=settings.client instanceof import_pubsub2.PubSub?settings.client:void 0;if(settings.client&&!client&&logger.debug("setup: settings.client is not a Pub/Sub SDK client; creating one for provisioning"),!client){const credentials=parseCredentials(resolveCredentials(config,logger),logger),clientOptions={projectId:projectId,...void 0!==credentials&&"string"!=typeof credentials?{credentials:credentials}:{},...settings.apiEndpoint?{apiEndpoint:settings.apiEndpoint}:{}};client=new import_pubsub2.PubSub(clientOptions),createdClient=!0}const topic=client.topic(topicName);let topicCreated=!1;const[exists]=await topic.exists();if(exists)logger.debug("setup: topic exists",{topic:topicName}),await async function(topic,declared,logger){let metadata;try{const[meta]=await topic.getMetadata();metadata=meta??{}}catch(err){return void logger.debug("setup: drift check failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(declared.messageStoragePolicy){const declaredRegions=declared.messageStoragePolicy.allowedPersistenceRegions,actualRegions=metadata.messageStoragePolicy?.allowedPersistenceRegions??[];(declaredRegions.length!==actualRegions.length||declaredRegions.some((r,i)=>r!==actualRegions[i]))&&logger.warn("setup.drift",{field:"messageStoragePolicy.allowedPersistenceRegions",declared:declaredRegions,actual:actualRegions})}if(declared.messageRetentionDuration){const declaredSeconds=declared.messageRetentionDuration.seconds,actualRaw=metadata.messageRetentionDuration?.seconds,actualSeconds="number"==typeof actualRaw?actualRaw:"string"==typeof actualRaw?Number(actualRaw):void 0;actualSeconds!==declaredSeconds&&logger.warn("setup.drift",{field:"messageRetentionDuration.seconds",declared:declaredSeconds,actual:actualSeconds??null})}void 0!==declared.kmsKeyName&&metadata.kmsKeyName!==declared.kmsKeyName&&logger.warn("setup.drift",{field:"kmsKeyName",declared:declared.kmsKeyName,actual:metadata.kmsKeyName??null});if(declared.labels){const actualLabels=metadata.labels??{};for(const[key,declaredValue]of Object.entries(declared.labels)){const actualValue=actualLabels[key];actualValue!==declaredValue&&logger.warn("setup.drift",{field:`labels.${key}`,declared:declaredValue,actual:actualValue??null})}}}(topic,merged,logger);else{const metadata={name:`projects/${projectId}/topics/${topicName}`};merged.messageStoragePolicy&&(metadata.messageStoragePolicy=merged.messageStoragePolicy),merged.messageRetentionDuration&&(metadata.messageRetentionDuration={seconds:merged.messageRetentionDuration.seconds}),merged.kmsKeyName&&(metadata.kmsKeyName=merged.kmsKeyName),merged.labels&&(metadata.labels=merged.labels);try{await client.createTopic(metadata),topicCreated=!0,logger.info("setup: topic created",{topic:topicName,projectId:projectId,messageStoragePolicy:metadata.messageStoragePolicy})}catch(err){if(!function(err){return function(err){return"object"==typeof err&&null!==err&&"code"in err&&"number"==typeof err.code}(err)&&(6===err.code||409===err.code)}(err))throw createdClient&&await safeClose(client,logger),err;logger.debug("setup: topic already exists (race)",{topic:topicName})}}return createdClient&&await safeClose(client,logger),{topicCreated:topicCreated}},init:async({config:partialConfig,env:env,logger:logger})=>function(partialConfig={},env,logger){const settings=partialConfig.settings??{},projectId="string"==typeof settings.projectId?settings.projectId:"",topic="string"==typeof settings.topic?settings.topic:"";projectId||logger.throw("Config settings projectId missing"),topic||logger.throw("Config settings topic missing");const credentials=parseCredentials(resolveCredentials(partialConfig,logger),logger);let client=settings.client;client||(client=new(env?.PubSub??import_pubsub.PubSub)(function(input){const result={projectId:input.projectId};return void 0!==input.credentials&&"string"!=typeof input.credentials&&(result.credentials=input.credentials),input.apiEndpoint&&(result.apiEndpoint=input.apiEndpoint),result}({projectId:projectId,credentials:credentials,apiEndpoint:settings.apiEndpoint})));const settingsConfig={...settings,client:client,projectId:projectId,topic:topic,credentials:credentials};return{...partialConfig,settings:settingsConfig}}(partialConfig,env,logger),push:async(event,context)=>await push2(event,context),async destroy({config:config}){if(!config.settings)return;const{client:client}=config.settings;if(client)try{await client.close()}catch{}}};//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";var mod,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,index_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(index_exports,{DestinationBigQuery:()=>types_exports,DestinationPubSub:()=>types_exports2,default:()=>destinationBigQuery,destinationBigQuery:()=>destinationBigQuery,destinationPubSub:()=>destinationPubSub}),module.exports=(mod=index_exports,((to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to})(__defProp({},"__esModule",{value:!0}),mod));var import_core7=require("@walkeros/core"),import_core2=require("@walkeros/core"),import_bigquery=require("@google-cloud/bigquery"),import_core=require("@walkeros/core"),import_pubsub=require("@google-cloud/pubsub");function resolveCredentials(partialConfig,logger){if(void 0!==partialConfig.credentials)return partialConfig.credentials;const fromSettings=partialConfig.settings?.credentials;return void 0!==fromSettings?(logger.warn("settings.credentials is deprecated; use config.credentials"),fromSettings):void 0}function parseCredentials(raw){if(void 0===raw)return;if("string"!=typeof raw)return raw;let parsed;try{parsed=JSON.parse(raw)}catch(err){throw new import_core.StepError("Invalid credentials JSON",{code:"config",cause:err})}if(!function(value){if(!(0,import_core.isObject)(value))return!1;const candidate=value;return"string"==typeof candidate.client_email&&"string"==typeof candidate.private_key}(parsed))throw new import_core.StepError("Invalid credentials JSON",{code:"config"});return parsed}var import_core4=require("@walkeros/core");function jsonOrNull(value){return null==value?null:"object"==typeof value?Array.isArray(value)&&0===value.length?null:Array.isArray(value)||0!==Object.keys(value).length?JSON.stringify(value):null:JSON.stringify(value)}function eventToRow(event){return{name:event.name,data:jsonOrNull(event.data),context:jsonOrNull(event.context),globals:jsonOrNull(event.globals),custom:jsonOrNull(event.custom),user:jsonOrNull(event.user),nested:jsonOrNull(event.nested),consent:jsonOrNull(event.consent),id:event.id,trigger:event.trigger,entity:event.entity,action:event.action,timestamp:1e3*new Date(event.timestamp).getTime(),timing:event.timing,source:jsonOrNull(event.source)}}var import_core3=require("@walkeros/core"),import_bigquery_storage=require("@google-cloud/bigquery-storage"),RETRYABLE_STATUS=[10,14,1,13,4];function appendError(outcome){if(!outcome.error)return;const status=outcome.error.code??void 0;return new import_core3.StepError(`BigQuery append failed (code ${status??"unknown"})`,{code:"transport",retryable:void 0!==status&&RETRYABLE_STATUS.includes(status)})}var MISSING_JSON_WRITER="BigQuery env: an injected WriterClient needs an injected JSONWriter; its connection cannot feed the SDK writer.",MissingJSONWriter=class{constructor(){throw new Error(MISSING_JSON_WRITER)}appendRows(){throw new Error(MISSING_JSON_WRITER)}close(){}};async function openWith({WriterClient:WriterClient,JSONWriter:JSONWriter,adapt:adaptFn},args,logger){const{projectId:projectId,datasetId:datasetId,tableId:tableId,credentials:credentials,bigquery:bigquery,timeout:timeout,onConnectionError:onConnectionError}=args,destinationTable=`projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;logger.debug("Opening BigQuery Storage Write API writer",{destinationTable:destinationTable});const callOptions=void 0===timeout?void 0:{timeout:timeout},writeClient=new WriterClient({projectId:projectId,...bigquery,...void 0!==credentials?{credentials:credentials}:{}});let connectionErrorListener,connection;try{connection=await writeClient.createStreamConnection({destinationTable:destinationTable,streamId:import_bigquery_storage.managedwriter.DefaultStream}),onConnectionError&&(connectionErrorListener=connection.onConnectionError(err=>{onConnectionError(err)}));const streamId=connection.getStreamId(),writeStream=await writeClient.getWriteStream({streamId:streamId,view:import_bigquery_storage.protos.google.cloud.bigquery.storage.v1.WriteStreamView.FULL},callOptions);if(!writeStream.tableSchema)throw new Error(`BigQuery write stream ${streamId} returned no tableSchema; cannot build proto descriptor`);const protoDescriptor=adaptFn.convertStorageSchemaToProto2Descriptor(writeStream.tableSchema,"root");return{writeClient:writeClient,writer:new JSONWriter({connection:connection,protoDescriptor:protoDescriptor}),connection:connection,connectionErrorListener:connectionErrorListener}}catch(err){throw closeWriter({writeClient:writeClient,connectionErrorListener:connectionErrorListener},logger),err}}function ensureWriter(settings,logger){const opening=!settings.writer;if(!opening&&!settings.writerBroken)return Promise.resolve();if(settings.reopenInFlight)return settings.reopenInFlight;const reopen=settings.reopenWriter;if(!reopen)return Promise.reject(new import_core3.StepError("BigQuery writer is not initialized",{code:"not-ready"}));opening||logger.info("BigQuery writer broken; attempting one re-open before failing");const inFlight=(async()=>{try{closeWriter({writer:settings.writer,writeClient:settings.writeClient,connectionErrorListener:settings.connectionErrorListener},logger);const handles=await reopen();settings.writeClient=handles.writeClient,settings.writer=handles.writer,settings.connection=handles.connection,settings.connectionErrorListener=handles.connectionErrorListener,settings.writerBroken=!1,settings.lastStreamError=void 0,opening||logger.info("BigQuery writer re-opened after a stream error")}finally{settings.reopenInFlight=void 0}})();return settings.reopenInFlight=inFlight,inFlight}function closeWriter(handles,logger){try{handles.connectionErrorListener?.off()}catch(err){logger.warn("connection error listener removal failed",{error:String(err)})}try{handles.writer?.close()}catch(err){logger.warn("writer.close failed",{error:String(err)})}try{handles.writeClient?.close()}catch(err){logger.warn("writeClient.close failed",{error:String(err)})}}var append=async function(event,{config:config,data:data,logger:logger}){const settings=config.settings;if(!settings)throw new import_core4.StepError("BigQuery settings missing, init() not run",{code:"not-ready"});await ensureWriter(settings,logger);const{writer:writer,datasetId:datasetId,tableId:tableId}=settings;if(!writer)throw new import_core4.StepError("BigQuery writer is missing",{code:"not-ready"});const rows=[(0,import_core4.isObject)(data)?data:eventToRow(event)];let result;logger.debug("Calling BigQuery Storage Write API",{dataset:datasetId,table:tableId,rowCount:rows.length});try{const pending=await writer.appendRows(rows);result=await pending.getResult()}catch(err){throw new import_core4.StepError("BigQuery row append threw",{code:"transport",cause:err})}const failed=appendError(result);if(failed)throw failed;if(result.rowErrors&&result.rowErrors.length>0)throw new import_core4.StepError(`BigQuery row append failed (code ${result.rowErrors[0].code})`,{code:"transport",retryable:!1});logger.debug("BigQuery Storage Write API response",{ok:!0,offset:result.appendResult?.offset?.value})},import_core5=require("@walkeros/core"),import_core6=require("@walkeros/core"),DEFAULT_SETUP={location:"EU",storageBillingModel:"PHYSICAL",partitioning:{type:"DAY",field:"timestamp"},clustering:{fields:["name","entity","action"]},schema:[{name:"name",type:"STRING",mode:"REQUIRED"},{name:"data",type:"JSON",mode:"NULLABLE"},{name:"context",type:"JSON",mode:"NULLABLE"},{name:"globals",type:"JSON",mode:"NULLABLE"},{name:"custom",type:"JSON",mode:"NULLABLE"},{name:"user",type:"JSON",mode:"NULLABLE"},{name:"nested",type:"JSON",mode:"NULLABLE"},{name:"consent",type:"JSON",mode:"NULLABLE"},{name:"id",type:"STRING",mode:"NULLABLE"},{name:"trigger",type:"STRING",mode:"NULLABLE"},{name:"entity",type:"STRING",mode:"NULLABLE"},{name:"action",type:"STRING",mode:"NULLABLE"},{name:"timestamp",type:"TIMESTAMP",mode:"NULLABLE"},{name:"timing",type:"FLOAT64",mode:"NULLABLE"},{name:"source",type:"JSON",mode:"NULLABLE"}]};function isAlreadyExists(err){return function(err){return"object"==typeof err&&null!==err&&("code"in err&&"number"==typeof err.code)}(err)&&409===err.code}var types_exports={},destinationBigQuery={type:"gcp-bigquery",config:{},setup:async function(ctx){const{config:config,logger:logger}=ctx,merged=(0,import_core6.resolveSetup)(config.setup,DEFAULT_SETUP);if(!merged)return void logger.debug("setup: skipped (config.setup is false or unset)");const options={location:merged.location??DEFAULT_SETUP.location,storageBillingModel:merged.storageBillingModel??DEFAULT_SETUP.storageBillingModel,partitioning:merged.partitioning??DEFAULT_SETUP.partitioning,clustering:merged.clustering??DEFAULT_SETUP.clustering,schema:merged.schema??DEFAULT_SETUP.schema};if(!config.settings)return void logger.throw("setup: settings missing");const{client:client,datasetId:datasetId,tableId:tableId}=config.settings;if(!client)return void logger.throw("setup: BigQuery client is missing");if(!datasetId)return void logger.throw("setup: datasetId is missing");if(!tableId)return void logger.throw("setup: tableId is missing");const dataset=client.dataset(datasetId);let datasetCreated=!1;const[datasetExists]=await dataset.exists();if(datasetExists)logger.debug("setup: dataset exists",{datasetId:datasetId});else try{await dataset.create({location:options.location,storageBillingModel:options.storageBillingModel}),datasetCreated=!0,logger.info("setup: dataset created",{datasetId:datasetId,location:options.location,storageBillingModel:options.storageBillingModel})}catch(err){if(!isAlreadyExists(err))throw err;logger.debug("setup: dataset already exists (race)",{datasetId:datasetId})}const table=dataset.table(tableId);let tableCreated=!1;const[tableExists]=await table.exists();if(tableExists)logger.debug("setup: table exists",{datasetId:datasetId,tableId:tableId}),await async function(table,options,logger){let metadata;try{const[meta]=await table.getMetadata();metadata=meta??{}}catch(err){return void logger.debug("setup: drift check failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(v=metadata.timePartitioning,"object"==typeof v&&null!==v){const actual=metadata.timePartitioning,declared=options.partitioning;actual.type===declared.type&&actual.field===declared.field||logger.warn("setup.drift",{field:"timePartitioning",declared:declared,actual:actual})}var v;if(function(v){return"object"==typeof v&&null!==v}(metadata.clustering)){const actualFields=metadata.clustering.fields??[],declaredFields=options.clustering.fields;(actualFields.length!==declaredFields.length||actualFields.some((f,i)=>f!==declaredFields[i]))&&logger.warn("setup.drift",{field:"clustering",declared:{fields:declaredFields},actual:{fields:actualFields}})}if(function(v){return"object"==typeof v&&null!==v}(metadata.schema)){const actualFields=metadata.schema.fields??[],declaredFields=options.schema;(actualFields.length!==declaredFields.length||declaredFields.some((d,i)=>{const a=actualFields[i];return!a||a.name!==d.name||a.type!==d.type||a.mode!==d.mode}))&&logger.warn("setup.drift",{field:"schema",declared:declaredFields.map(f=>({name:f.name,type:f.type,mode:f.mode})),actual:actualFields.map(f=>({name:f.name,type:f.type,mode:f.mode}))})}}(table,options,logger);else try{await table.create({schema:{fields:options.schema},timePartitioning:{type:options.partitioning.type,field:options.partitioning.field},clustering:{fields:options.clustering.fields}}),tableCreated=!0,logger.info("setup: table created",{datasetId:datasetId,tableId:tableId,partitioning:options.partitioning,clustering:options.clustering})}catch(err){if(!isAlreadyExists(err))throw err;logger.debug("setup: table already exists (race)",{tableId:tableId})}return{datasetCreated:datasetCreated,tableCreated:tableCreated}},async init({config:partialConfig,env:env,logger:logger,id:id,reportError:reportError}){const config=function(partialConfig={},env){const settings=partialConfig.settings||{},{projectId:projectId,bigquery:bigquery}=settings;let{client:client,location:location,datasetId:datasetId,tableId:tableId}=settings;if(!projectId)throw new import_core2.StepError("Config settings projectId missing",{code:"config"});location=location||"EU",datasetId=datasetId||"walkerOS",tableId=tableId||"events";const options={...bigquery||{}};options.projectId=projectId;const parsed=parseCredentials(partialConfig.credentials),credentials=void 0!==parsed&&"string"!=typeof parsed?parsed:void 0;void 0!==credentials&&(options.credentials=credentials);const BigQueryClass=env?.BigQuery||import_bigquery.BigQuery;client=client||new BigQueryClass(options);const settingsConfig={...settings,client:client,projectId:projectId,location:location,datasetId:datasetId,tableId:tableId,...void 0!==credentials?{credentials:credentials}:{}};return{...partialConfig,settings:settingsConfig}}(partialConfig,env),timeout=config.timeout&&config.timeout>0?config.timeout:1e4,{settings:settings}=config,onConnectionError=err=>{settings.writerBroken=!0,settings.lastStreamError=err instanceof Error?err:new Error(String(err)),reportError?.(err)};return settings.reopenWriter=()=>function(args,logger){const{env:env}=args;if(!env?.WriterClient)return openWith({WriterClient:import_bigquery_storage.managedwriter.WriterClient,JSONWriter:env?.JSONWriter??import_bigquery_storage.managedwriter.JSONWriter,adapt:env?.adapt??import_bigquery_storage.adapt},args,logger);return openWith({WriterClient:env.WriterClient,JSONWriter:env.JSONWriter??MissingJSONWriter,adapt:env.adapt??import_bigquery_storage.adapt},args,logger)}({projectId:settings.projectId,datasetId:settings.datasetId,tableId:settings.tableId,credentials:settings.credentials,bigquery:settings.bigquery,timeout:timeout,onConnectionError:onConnectionError,env:env},logger).catch(err=>{throw function(err,settings,id){return function(err){if("object"!=typeof err||null===err)return!1;if(!("code"in err))return!1;const obj=err;return 5===obj.code||404===obj.code}(err)?new import_core7.StepError(`BigQuery dataset or table not found: project="${settings.projectId}", target="${settings.datasetId}.${settings.tableId}". Run "walkeros setup destination.${id}" to create them.`,{code:"config",cause:err}):new import_core7.StepError("BigQuery writer could not be opened",{code:"transport",cause:err})}(err,settings,id)}),config},push:async(event,context)=>await async function(event,context){context.rule?.silent||await append(event,context)}(event,context),pushBatch:async(batch,{config:config,logger:logger})=>{const settings=config.settings;if(!settings)throw new import_core5.StepError("BigQuery settings missing, init() not run",{code:"not-ready"});const sent=batch.entries.flatMap((entry,index)=>entry.rule?.silent?[]:[{entry:entry,index:index}]);if(0===sent.length)return;await ensureWriter(settings,logger);const{writer:writer,datasetId:datasetId,tableId:tableId}=settings;if(!writer)throw new import_core5.StepError("BigQuery writer is missing",{code:"not-ready"});const rows=sent.map(({entry:entry})=>(0,import_core5.isObject)(entry.data)?entry.data:eventToRow(entry.event));let result;logger.debug("Calling BigQuery Storage Write API (batch)",{dataset:datasetId,table:tableId,rowCount:rows.length});try{const pending=await writer.appendRows(rows);result=await pending.getResult()}catch(err){throw new import_core5.StepError("BigQuery batch append threw",{code:"transport",cause:err})}const failed=appendError(result);if(failed)throw failed;if(result.rowErrors&&result.rowErrors.length>0){return{failed:result.rowErrors.map(re=>({index:sent[Number(re.index)]?.index??Number(re.index),error:new import_core5.StepError(`BigQuery row append failed (code ${re.code})`,{code:"transport",retryable:!1})}))}}logger.debug("BigQuery batch append ok",{ok:rows.length,failed:0,offset:result.appendResult?.offset?.value})},async destroy({config:config,logger:logger}){config.settings&&closeWriter({writer:config.settings.writer,writeClient:config.settings.writeClient,connectionErrorListener:config.settings.connectionErrorListener},logger)}};var import_core8=require("@walkeros/core"),RETRYABLE_GRPC=[1,2,4,8,10,13,14];function hasNumericCode(err){if("object"!=typeof err||null===err)return!1;if(!("code"in err))return!1;return"number"==typeof err.code}var publish=async function(event,{config:config,rule:rule,data:data,collector:collector,logger:logger,id:id}){const settings=config.settings;if(!function(value){if("object"!=typeof value||null===value)return!1;const candidate=value;return void 0!==candidate.client&&"string"==typeof candidate.projectId&&candidate.projectId.length>0&&"string"==typeof candidate.topic&&candidate.topic.length>0}(settings))throw new import_core8.StepError("Pub/Sub settings missing or incomplete, init() not run",{code:"not-ready"});const{client:client,projectId:projectId,topic:defaultTopic}=settings,ruleSettings=(value=rule?.settings,"object"==typeof value&&null!==value?rule.settings:{});var value;const topicName="string"==typeof ruleSettings.topic&&ruleSettings.topic.length>0?ruleSettings.topic:defaultTopic,orderingValue=void 0!==ruleSettings.orderingKey?ruleSettings.orderingKey:settings.orderingKey;let orderingKey;if(void 0!==orderingValue){const resolved=await(0,import_core8.getMappingValue)(event,orderingValue,{collector:collector});"string"==typeof resolved&&resolved.length>0?orderingKey=resolved:null!=resolved&&(orderingKey=String(resolved))}const topicHandle=client.topic(topicName,{messageOrdering:Boolean(orderingKey)}),body=(0,import_core8.isObject)(data)&&Object.keys(data).length>0?data:event,payload=Buffer.from(JSON.stringify(body)),baseAttrs=settings.attributes,ruleAttrs=ruleSettings.attributes,attributes=await async function(event,base,override,collector){const result={};let touched=!1;if(base)for(const[key,value]of Object.entries(base)){const resolved=await(0,import_core8.getMappingValue)(event,value,{collector:collector});"string"==typeof resolved?(result[key]=resolved,touched=!0):null!=resolved&&(result[key]=String(resolved),touched=!0)}if(override)for(const[key,value]of Object.entries(override)){const resolved=await(0,import_core8.getMappingValue)(event,value,{collector:collector});"string"==typeof resolved?(result[key]=resolved,touched=!0):null!=resolved&&(result[key]=String(resolved),touched=!0)}return touched?result:void 0}(event,baseAttrs,ruleAttrs,collector),message={data:payload};attributes&&function(value){if(!(0,import_core8.isObject)(value))return!1;const candidate=value;for(const key of Object.keys(candidate))if("string"!=typeof candidate[key])return!1;return!0}(attributes)&&(message.attributes=attributes),orderingKey&&(message.orderingKey=orderingKey),logger.debug("Pub/Sub publish",{topic:topicName,projectId:projectId,event:event.name});try{await topicHandle.publishMessage(message)}catch(err){if(orderingKey)try{topicHandle.resumePublishing(orderingKey)}catch(resumeErr){logger.debug("Pub/Sub resumePublishing failed",{topic:topicName,error:resumeErr instanceof Error?resumeErr.message:String(resumeErr)})}if(function(err){return hasNumericCode(err)&&(5===err.code||404===err.code)}(err))throw new import_core8.StepError(`Pub/Sub topic "${topicName}" not found in project "${projectId}". Run "walkeros setup destination.${id}" to create it.`,{code:"config",cause:err});if(function(err){return hasNumericCode(err)&&(7===err.code||16===err.code||403===err.code||401===err.code)}(err))throw new import_core8.StepError(`Pub/Sub publish denied for topic "${topicName}". Grant the runtime service account roles/pubsub.publisher on this topic.`,{code:"config",cause:err});if(!hasNumericCode(err))throw new import_core8.StepError("Pub/Sub publish failed",{code:"transport",cause:err});throw new import_core8.StepError(`Pub/Sub publish failed (code ${err.code})`,{code:"transport",...err.code>16?{status:err.code}:{retryable:RETRYABLE_GRPC.includes(err.code)},cause:err})}},import_core9=require("@walkeros/core"),import_pubsub2=require("@google-cloud/pubsub"),DEFAULT_SETUP2={messageStoragePolicy:{allowedPersistenceRegions:["europe-west1","europe-west3","europe-west4"]}};async function safeClose(client,logger){try{await client.close()}catch(err){logger.debug("setup: client.close failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}var types_exports2={},destinationPubSub={type:"gcp-pubsub",config:{},setup:async function(ctx){const{config:config,logger:logger}=ctx,merged=(0,import_core9.resolveSetup)(config.setup,DEFAULT_SETUP2);if(!merged)return void logger.debug("setup: skipped (config.setup is false or unset)");const settings=config.settings;if(!settings)return void logger.throw("setup: settings missing");const projectId="string"==typeof settings.projectId?settings.projectId:"",topicName="string"==typeof settings.topic?settings.topic:"";if(!projectId)return void logger.throw("setup: projectId is missing");if(!topicName)return void logger.throw("setup: topic is missing");let createdClient=!1,client=settings.client instanceof import_pubsub2.PubSub?settings.client:void 0;if(settings.client&&!client&&logger.debug("setup: settings.client is not a Pub/Sub SDK client; creating one for provisioning"),!client){const credentials=parseCredentials(resolveCredentials(config,logger)),clientOptions={projectId:projectId,...void 0!==credentials&&"string"!=typeof credentials?{credentials:credentials}:{},...settings.apiEndpoint?{apiEndpoint:settings.apiEndpoint}:{}};client=new import_pubsub2.PubSub(clientOptions),createdClient=!0}const topic=client.topic(topicName);let topicCreated=!1;const[exists]=await topic.exists();if(exists)logger.debug("setup: topic exists",{topic:topicName}),await async function(topic,declared,logger){let metadata;try{const[meta]=await topic.getMetadata();metadata=meta??{}}catch(err){return void logger.debug("setup: drift check failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(declared.messageStoragePolicy){const declaredRegions=declared.messageStoragePolicy.allowedPersistenceRegions,actualRegions=metadata.messageStoragePolicy?.allowedPersistenceRegions??[];(declaredRegions.length!==actualRegions.length||declaredRegions.some((r,i)=>r!==actualRegions[i]))&&logger.warn("setup.drift",{field:"messageStoragePolicy.allowedPersistenceRegions",declared:declaredRegions,actual:actualRegions})}if(declared.messageRetentionDuration){const declaredSeconds=declared.messageRetentionDuration.seconds,actualRaw=metadata.messageRetentionDuration?.seconds,actualSeconds="number"==typeof actualRaw?actualRaw:"string"==typeof actualRaw?Number(actualRaw):void 0;actualSeconds!==declaredSeconds&&logger.warn("setup.drift",{field:"messageRetentionDuration.seconds",declared:declaredSeconds,actual:actualSeconds??null})}void 0!==declared.kmsKeyName&&metadata.kmsKeyName!==declared.kmsKeyName&&logger.warn("setup.drift",{field:"kmsKeyName",declared:declared.kmsKeyName,actual:metadata.kmsKeyName??null});if(declared.labels){const actualLabels=metadata.labels??{};for(const[key,declaredValue]of Object.entries(declared.labels)){const actualValue=actualLabels[key];actualValue!==declaredValue&&logger.warn("setup.drift",{field:`labels.${key}`,declared:declaredValue,actual:actualValue??null})}}}(topic,merged,logger);else{const metadata={name:`projects/${projectId}/topics/${topicName}`};merged.messageStoragePolicy&&(metadata.messageStoragePolicy=merged.messageStoragePolicy),merged.messageRetentionDuration&&(metadata.messageRetentionDuration={seconds:merged.messageRetentionDuration.seconds}),merged.kmsKeyName&&(metadata.kmsKeyName=merged.kmsKeyName),merged.labels&&(metadata.labels=merged.labels);try{await client.createTopic(metadata),topicCreated=!0,logger.info("setup: topic created",{topic:topicName,projectId:projectId,messageStoragePolicy:metadata.messageStoragePolicy})}catch(err){if(!function(err){return function(err){return"object"==typeof err&&null!==err&&"code"in err&&"number"==typeof err.code}(err)&&(6===err.code||409===err.code)}(err))throw createdClient&&await safeClose(client,logger),err;logger.debug("setup: topic already exists (race)",{topic:topicName})}}return createdClient&&await safeClose(client,logger),{topicCreated:topicCreated}},init:async({config:partialConfig,env:env,logger:logger})=>function(partialConfig={},env,logger){const settings=partialConfig.settings??{},projectId="string"==typeof settings.projectId?settings.projectId:"",topic="string"==typeof settings.topic?settings.topic:"";if(!projectId||!topic){const missing=[...projectId?[]:["projectId"],...topic?[]:["topic"]];throw new import_core.StepError(`Config settings ${missing.join(", ")} missing`,{code:"config"})}const credentials=parseCredentials(resolveCredentials(partialConfig,logger));let client=settings.client;client||(client=new(env?.PubSub??import_pubsub.PubSub)(function(input){const result={projectId:input.projectId};return void 0!==input.credentials&&"string"!=typeof input.credentials&&(result.credentials=input.credentials),input.apiEndpoint&&(result.apiEndpoint=input.apiEndpoint),result}({projectId:projectId,credentials:credentials,apiEndpoint:settings.apiEndpoint})));const settingsConfig={...settings,client:client,projectId:projectId,topic:topic,credentials:credentials};return{...partialConfig,settings:settingsConfig}}(partialConfig,env,logger),push:async(event,context)=>await async function(event,context){context.rule?.silent||await publish(event,context)}(event,context),async destroy({config:config}){if(!config.settings)return;const{client:client}=config.settings;if(client)try{await client.close()}catch{}}};//# sourceMappingURL=index.js.map
|