@flatfile/listener 0.3.2 → 0.3.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flatfile/listener",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "A PubSub Listener for configuring and using Flatfile",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -12,6 +12,9 @@
12
12
  "poll": "tsup src/dev.ts --format esm,cjs --watch --dts --onSuccess \"node dist/dev.js\"",
13
13
  "test": "jest --passWithNoTests"
14
14
  },
15
+ "files": [
16
+ "dist/**"
17
+ ],
15
18
  "license": "MIT",
16
19
  "devDependencies": {
17
20
  "@flatfile/eslint-config-platform-sdk": "*",
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- export default {
2
- root: true,
3
- extends: ['@flatfile/eslint-config-platform-sdk'],
4
- }
@@ -1,17 +0,0 @@
1
-
2
- > @flatfile/listener@0.3.2 build
3
- > tsup src/index.ts --format esm,cjs --dts
4
-
5
- CLI Building entry: src/index.ts
6
- CLI Using tsconfig: tsconfig.json
7
- CLI tsup v6.7.0
8
- CLI Target: es2020
9
- ESM Build start
10
- CJS Build start
11
- ESM dist/index.mjs 16.07 KB
12
- ESM ⚡️ Build success in 81ms
13
- CJS dist/index.js 18.01 KB
14
- CJS ⚡️ Build success in 81ms
15
- DTS Build start
16
- DTS ⚡️ Build success in 2157ms
17
- DTS dist/index.d.ts 7.32 KB
package/CHANGELOG.md DELETED
@@ -1,113 +0,0 @@
1
- # @flatfile/listener
2
-
3
- ## 0.3.2
4
-
5
- ### Patch Changes
6
-
7
- - 84f6807: resolves a minor bug with afterAll callbacks and adds recursive listener introspection
8
-
9
- ## 0.3.1
10
-
11
- ### Patch Changes
12
-
13
- - 9ca9443: Event Cache Cleanup
14
-
15
- ## 0.3.0
16
-
17
- ### Minor Changes
18
-
19
- - 2a30e13: Add cross-env library for accessing environment variables
20
-
21
- ## 0.2.0
22
-
23
- ### Minor Changes
24
-
25
- - 637342b: Remove @flatfile/api from listener
26
-
27
- ## 0.1.2
28
-
29
- ### Patch Changes
30
-
31
- - 22d2466: Pull last 5 seconds of events in Polling Driver
32
-
33
- ## 0.1.1
34
-
35
- ### Patch Changes
36
-
37
- - 356c35d: Minor CI improvements and backwards compatible rename of Client to FlatfileListener
38
-
39
- ## 0.1.0
40
-
41
- ### Minor Changes
42
-
43
- - 4d88069: Adds a major improvement to event filtering, allowing you to grep the key path and defaulting to matching any key in the object
44
-
45
- ## 0.0.10
46
-
47
- ### Patch Changes
48
-
49
- - 4807720: removes unused node dependencies
50
- - 82e80e3: Add in x-disable-hooks header
51
-
52
- ## 0.0.9
53
-
54
- ### Patch Changes
55
-
56
- - 46357d9: flatfile deploy and develop
57
-
58
- ## 0.0.8
59
-
60
- ### Patch Changes
61
-
62
- - 74852f3: Adds Event Cache
63
- - 65aea7a: Adds conditional fetchApi variable to authenticated client to allow for client-side use
64
-
65
- ## 0.0.7
66
-
67
- ### Patch Changes
68
-
69
- - Updated dependencies [72447b1]
70
- - @flatfile/hooks@1.3.0
71
-
72
- ## 0.0.6
73
-
74
- ### Patch Changes
75
-
76
- - 4039970: Adds 'x-disable-hooks': 'true' to event payload to x
77
-
78
- ## 0.0.5
79
-
80
- ### Patch Changes
81
-
82
- - 55f9fff: Update API version and use configless space creation in listener example.
83
- - Updated dependencies [55f9fff]
84
- - @flatfile/schema@0.2.15
85
-
86
- ## 0.0.4
87
-
88
- ### Patch Changes
89
-
90
- - 8ed4e8c: Bumps API version and adds support for record metadata to @flatfile/hooks.
91
- - Updated dependencies [8ed4e8c]
92
- - @flatfile/schema@0.2.14
93
- - @flatfile/hooks@1.2.4
94
-
95
- ## 0.0.3
96
-
97
- ### Patch Changes
98
-
99
- - c946831: Updates to use the dataUrl for getting records
100
-
101
- ## 0.0.2
102
-
103
- ### Patch Changes
104
-
105
- - 2e25be3: Update packages with updated @flatfile/api
106
- - Updated dependencies [2e25be3]
107
- - @flatfile/schema@0.2.13
108
-
109
- ## 0.0.1
110
-
111
- ### Patch Changes
112
-
113
- - 4b918a2: Adds the new @flatfile/listener package
package/jest.config.js DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- preset: '@flatfile/jest-preset-platform-sdk',
3
- }
@@ -1,37 +0,0 @@
1
- import { EventDriver } from './_EventDriver'
2
- import { EventHandler } from '../events'
3
-
4
- export class Browser extends EventDriver {
5
- public _accessToken?: string
6
- public _apiUrl?: string
7
- public _environmentId?: string
8
-
9
- constructor({
10
- apiUrl,
11
- accessToken,
12
- environmentId,
13
- }: {
14
- apiUrl: string
15
- accessToken: string
16
- environmentId?: string
17
- /**
18
- * @deprecated
19
- */
20
- fetchApi: any
21
- }) {
22
- super()
23
- this._apiUrl = apiUrl
24
- this._accessToken = accessToken
25
- this._environmentId = environmentId || ''
26
- }
27
-
28
- mountEventHandler(handler: EventHandler): this {
29
- handler.setVariables({
30
- accessToken: this._accessToken,
31
- apiUrl: this._apiUrl,
32
- })
33
-
34
- this._handler = handler
35
- return this
36
- }
37
- }
@@ -1,25 +0,0 @@
1
- import { EventDriver } from './_EventDriver'
2
- import { EventHandler, FlatfileEvent } from '../events'
3
-
4
- /**
5
- * Flatfile's Virtual Machine is stateless / serverless. So when a new event
6
- * is handled, it will just call `handle(event)`.
7
- */
8
- export class FlatfileVirtualMachine extends EventDriver {
9
- /**
10
- * This method is triggered from within the Flatfile Core VM Runner. This
11
- * EventDriver does not have to listen for events because this method will
12
- * be invoked as necessary.
13
- *
14
- * @param event
15
- */
16
-
17
- handle(event: FlatfileEvent) {
18
- this.dispatchEvent(event)
19
- }
20
-
21
- mountEventHandler(handler: EventHandler): this {
22
- this._handler = handler
23
- return this
24
- }
25
- }
File without changes
@@ -1,32 +0,0 @@
1
- import { EventHandler } from '../events'
2
-
3
- export abstract class EventDriver {
4
- _handler?: EventHandler
5
-
6
- public get handler(): EventHandler {
7
- if (!this._handler) {
8
- throw new Error('handler not registered yet')
9
- }
10
- return this._handler
11
- }
12
-
13
- /**
14
- * Mount an event handler
15
- *
16
- * @param handler
17
- */
18
- mountEventHandler(handler: EventHandler): this {
19
- this._handler = handler
20
- return this
21
- }
22
-
23
- /**
24
- * Dispatch an event
25
- *
26
- * @param e
27
- */
28
- dispatchEvent(e: any): this {
29
- this.handler.dispatchEvent(e)
30
- return this
31
- }
32
- }
@@ -1,3 +0,0 @@
1
- export * from './Browser'
2
- export * from './FlatfileVirtualMachine'
3
- export * from './_EventDriver'
@@ -1,44 +0,0 @@
1
- import { CrossEnvConfig } from '@flatfile/cross-env-config'
2
- import axios from 'axios'
3
-
4
- export class AuthenticatedClient {
5
- public _accessToken?: string
6
- public _apiUrl?: string
7
-
8
- constructor(accessToken?: string, apiUrl?: string) {
9
- const FLATFILE_API_URL =
10
- CrossEnvConfig.get('AGENT_INTERNAL_URL') || 'http://localhost:3000'
11
- const bearerToken = CrossEnvConfig.get('FLATFILE_BEARER_TOKEN')
12
-
13
- this._accessToken = accessToken || bearerToken || '...'
14
-
15
- this._apiUrl = apiUrl || FLATFILE_API_URL
16
- }
17
-
18
- fetch(url: string) {
19
- const headers = {
20
- Authorization: `Bearer ${this._accessToken}`,
21
- 'x-disable-hooks': 'true',
22
- }
23
- const fetchUrl = this._apiUrl + '/' + url
24
-
25
- return axios
26
- .get(fetchUrl, { headers })
27
- .then((resp: any) => resp.data.data)
28
- .catch((err: any) => {})
29
- }
30
- /**
31
- *
32
- * @deprecated use @flatfile/cross-env-config instead
33
- */
34
- public setVariables({
35
- accessToken,
36
- apiUrl,
37
- }: {
38
- accessToken?: string
39
- apiUrl?: string
40
- }) {
41
- this._accessToken = accessToken
42
- this._apiUrl = apiUrl
43
- }
44
- }
@@ -1,45 +0,0 @@
1
- export class EventCache {
2
- private eventCache: Map<any, any> = new Map()
3
-
4
- async init<T>(key: string, callback: () => Promise<T>): Promise<T> {
5
- if (this.eventCache.get(key)) {
6
- return this.eventCache.get(key)
7
- } else {
8
- const result = await callback()
9
- this.eventCache.set(key, result)
10
- return result
11
- }
12
- }
13
-
14
- async set<T>(key: string, callback: () => Promise<T>): Promise<T> {
15
- if (this.eventCache.get(key)) {
16
- const result = await callback()
17
- this.eventCache.set(key, result)
18
- return result
19
- } else {
20
- throw new Error('Cache key not found')
21
- }
22
- }
23
-
24
- get<T>(key: string): T {
25
- if (this.eventCache.get(key)) {
26
- return this.eventCache.get(key)
27
- } else {
28
- throw new Error('Cache key not found')
29
- }
30
- }
31
-
32
- delete(key?: string | string[]): void {
33
- if (!key) {
34
- this.eventCache.clear()
35
- } else if (this.eventCache.get(key)) {
36
- if (Array.isArray(key)) {
37
- key.forEach((k) => this.eventCache.delete(k))
38
- } else {
39
- this.eventCache.delete(key)
40
- }
41
- } else {
42
- throw new Error('Cache key not found')
43
- }
44
- }
45
- }
@@ -1,89 +0,0 @@
1
- import { EventHandler } from './event.handler'
2
-
3
- describe('EventHandler', () => {
4
- let testFn: jest.Mock
5
-
6
- beforeEach(() => {
7
- testFn = jest.fn()
8
- })
9
-
10
- describe('triggering', () => {
11
- test('triggers basic event listeners', () => {
12
- const handler = new EventHandler().on('foo', testFn)
13
-
14
- handler.dispatchEvent({ topic: 'foo' })
15
- expect(testFn).toHaveBeenCalledTimes(1)
16
- })
17
-
18
- test('triggers namespaced event listeners', () => {
19
- const handler = new EventHandler().on('records:created', testFn)
20
-
21
- handler.dispatchEvent({ topic: 'records:created' })
22
- expect(testFn).toHaveBeenCalled()
23
- })
24
-
25
- test('triggers event listener for array of events', () => {
26
- const handler = new EventHandler().on(
27
- ['records:created', 'records:updated'],
28
- testFn
29
- )
30
-
31
- handler.dispatchEvent({ topic: 'records:created' })
32
- handler.dispatchEvent({ topic: 'records:updated' })
33
- expect(testFn).toHaveBeenCalledTimes(2)
34
- })
35
-
36
- test('triggers event listener for wildcard query of events', () => {
37
- const handler = new EventHandler().on('records:*', testFn)
38
-
39
- handler.dispatchEvent({ topic: 'records:created' })
40
- handler.dispatchEvent({ topic: 'records:updated' })
41
- handler.dispatchEvent({ topic: 'records:deleted' })
42
- expect(testFn).toHaveBeenCalledTimes(3)
43
- })
44
- })
45
-
46
- describe('filtering', () => {
47
- test('trigger only when filter match - on listener', () => {
48
- const handler = new EventHandler().on(
49
- 'records:created',
50
- { domain: 'foo' },
51
- testFn
52
- )
53
-
54
- handler.dispatchEvent({ topic: 'records:created' })
55
- handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
56
- expect(testFn).toHaveBeenCalledTimes(1)
57
- })
58
-
59
- test('trigger only when filter match - on scope', () => {
60
- const handler = new EventHandler({ domain: 'foo' }).on(
61
- 'records:created',
62
- testFn
63
- )
64
-
65
- handler.dispatchEvent({ topic: 'records:created' })
66
- handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
67
- expect(testFn).toHaveBeenCalledTimes(1)
68
- })
69
- })
70
-
71
- describe('child node', () => {
72
- test('trigger a listener on a child node', async () => {
73
- const handler = new EventHandler().addNode(
74
- new EventHandler().on('records:created', testFn)
75
- )
76
- await handler.dispatchEvent({ topic: 'records:created' })
77
- expect(testFn).toHaveBeenCalledTimes(1)
78
- })
79
-
80
- test('trigger only when filter match - on scope', async () => {
81
- const handler = new EventHandler().addNode(
82
- new EventHandler({ domain: 'foo' }).on('records:created', testFn)
83
- )
84
- await handler.dispatchEvent({ topic: 'records:created' })
85
- await handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
86
- expect(testFn).toHaveBeenCalledTimes(1)
87
- })
88
- })
89
- })
@@ -1,192 +0,0 @@
1
- import { AuthenticatedClient } from './authenticated.client'
2
- import { EventCallback, FlatfileEvent } from './flatfile.event'
3
- import { glob, objectMatches } from './glob.match'
4
- import type { Flatfile } from '@flatfile/api'
5
-
6
- /**
7
- * EventHandler is a Flatfile flavored implementation of EventTarget
8
- */
9
- export class EventHandler extends AuthenticatedClient {
10
- /**
11
- * Apply a filter to the values of an event
12
- */
13
- public readonly filterQuery?: EventFilter
14
-
15
- /**
16
- * Cache of registered listeners on this instance
17
- * @private
18
- */
19
- private listeners: [string | string[], EventFilter, EventCallback][] = []
20
-
21
- constructor(filter?: EventFilter, accessToken?: string, apiUrl?: string) {
22
- super(accessToken, apiUrl)
23
- if (filter) {
24
- this.filterQuery = filter
25
- }
26
- }
27
-
28
- /**
29
- * Cache of registered child nodes for this listener. These nodes will
30
- * only receive events that pass the parent filter.
31
- *
32
- * @private
33
- */
34
- private nodes: EventHandler[] = []
35
-
36
- /**
37
- * Register a subscriber for events that match this path
38
- */
39
- on(query: Arrayable<string>, callback: EventCallback): this
40
- on(
41
- query: Arrayable<string>,
42
- filter: EventFilter,
43
- callback: EventCallback
44
- ): this
45
- on(
46
- query: Arrayable<string>,
47
- ...rest: [EventCallback] | [EventFilter, EventCallback]
48
- ): this {
49
- let filter: EventFilter = {}
50
- const callback: EventCallback = rest.pop() as EventCallback
51
-
52
- if (rest.length) {
53
- filter = rest.shift() as EventFilter
54
- }
55
-
56
- this.listeners.push([query, filter, callback])
57
-
58
- return this
59
- }
60
-
61
- /**
62
- * Add child nodes to send this event to as well
63
- *
64
- * @param node
65
- */
66
- addNode(node: EventHandler): this {
67
- this.nodes.push(node)
68
- return this
69
- }
70
-
71
- /**
72
- * Dispatch an event and resolve the promise once it has completed (or
73
- * errored
74
- *
75
- * @todo - is there a right order in which to resolve event listeners?
76
- * Should it matter?
77
- *
78
- * @param event
79
- */
80
- async dispatchEvent(
81
- event: FlatfileEvent | Flatfile.Event | any
82
- ): Promise<void> {
83
- if (!(event instanceof FlatfileEvent)) {
84
- event = new FlatfileEvent(event, this._accessToken, this._apiUrl)
85
- if (this._apiUrl && this._accessToken) {
86
- event.setVariables({
87
- apiUrl: this._apiUrl,
88
- accessToken: this._accessToken,
89
- })
90
- }
91
- }
92
-
93
- await this.trigger(event, true)
94
-
95
- await event.afterAllCallbacks.forEach(async (cb: any) => cb(event))
96
- event.cache.delete()
97
- }
98
-
99
- /**
100
- * @deprecated legacy shim for receiving events from the VM layer
101
- * @alias dispatchEvent
102
- * @param event
103
- */
104
- async routeEvent(event: Flatfile.Event) {
105
- return this.dispatchEvent(event)
106
- }
107
-
108
- /**
109
- * Actually trigger the event listeners on this particular target
110
- *
111
- * @note It is safer for now to run this in series to avoid IO locks and
112
- * potential race conditions and uncaught errors
113
- *
114
- * @param event
115
- * @param recursive
116
- */
117
- async trigger(
118
- event: FlatfileEvent,
119
- recursive: boolean = false
120
- ): Promise<void> {
121
- const listeners = this.getListeners(event, recursive)
122
- for (const cb of listeners) {
123
- await cb.callback(event)
124
- }
125
- }
126
-
127
- /**
128
- * Get any listeners from this target subscribing to this event
129
- *
130
- * @param event
131
- * @param recursive
132
- */
133
- public getListeners(
134
- event: FlatfileEvent,
135
- recursive: boolean = false
136
- ): Listener[] {
137
- // never return any listeners if the event doesn't match the filter
138
- // event recursion should not occur either
139
- if (!this.matchEvent(event, this.filterQuery)) {
140
- return []
141
- }
142
-
143
- // look at listeners registered here
144
- const listeners = this.listeners
145
- .filter(([query, filter]) => {
146
- const globbed = glob(event.topic, query)
147
- const matched = this.matchEvent(event, filter)
148
- return globbed && matched
149
- })
150
- .map(([query, filter, callback]) => ({ query, filter, callback }))
151
-
152
- return !recursive
153
- ? listeners
154
- : [
155
- ...listeners,
156
- ...this.nodes.flatMap((n) => n.getListeners(event, true)),
157
- ]
158
- }
159
-
160
- /**
161
- * Attach more event listeners using a callback function. Used most
162
- * frequently for plugins.
163
- *
164
- * @param fn
165
- */
166
- use(fn: (handler: this) => void) {
167
- fn(this)
168
- return this
169
- }
170
-
171
- /**
172
- * Filter an event out based on glob filter object
173
- *
174
- * @param event
175
- * @param filter
176
- */
177
- public matchEvent(
178
- event: FlatfileEvent,
179
- filter: EventFilter | undefined
180
- ): boolean {
181
- return filter ? objectMatches(event, filter) : true
182
- }
183
- }
184
-
185
- export type EventFilter = Record<string, Arrayable<string>>
186
-
187
- export type Arrayable<T> = T | Array<T>
188
- export type Listener = {
189
- query: string | string[]
190
- filter: any
191
- callback: EventCallback
192
- }
@@ -1,66 +0,0 @@
1
- import { AuthenticatedClient } from './authenticated.client'
2
- import type { Flatfile } from '@flatfile/api'
3
- import { EventCache } from './cache'
4
- export class FlatfileEvent extends AuthenticatedClient {
5
- /**
6
- * Event ID from the API
7
- *
8
- * @example us0_ev_82hgidh9skd
9
- * @readonly
10
- *
11
- */
12
- public readonly id?: string
13
-
14
- /**
15
- * Topic the event was produced on
16
- *
17
- * @example workbook:created
18
- * @readonly
19
- */
20
- public readonly topic: string
21
- public readonly domain: string
22
- public readonly target: string
23
- public readonly action: string
24
- public readonly context: any
25
- public readonly payload: any
26
- public readonly cache: EventCache
27
-
28
- constructor(
29
- private readonly src: Flatfile.Event,
30
- accessToken?: string,
31
- apiUrl?: string
32
- ) {
33
- super(accessToken, apiUrl)
34
- this.cache = new EventCache()
35
- this.domain = src.domain
36
- this.topic = src.topic
37
- this.context = src.context // -> [us0_acc_ihjh8943h9w, space_id, workbook_id]
38
- this.payload = src.payload
39
- this.target = src.target || ''
40
- this.action = src.context?.actionName || ''
41
- }
42
-
43
- /**
44
- * Should return either event body if expanded already or fetch data from the
45
- * signed callback URL
46
- *
47
- * @todo this should work with the included callback URL
48
- */
49
- get data(): Promise<any> {
50
- if (this.src.dataUrl) {
51
- return this.fetch(this.src.dataUrl)
52
- } else {
53
- return this.payload
54
- }
55
- }
56
-
57
- private afterAllCallbacks: Map<any, any> = new Map()
58
- afterAll<T>(callback: () => T, cacheKey?: string): void {
59
- const key = cacheKey || callback.toString()
60
- if (!this.afterAllCallbacks.get(key)) {
61
- this.afterAllCallbacks.set(key, callback)
62
- }
63
- }
64
- }
65
-
66
- export type EventCallback = (evt: FlatfileEvent) => void
@@ -1,231 +0,0 @@
1
- import { objectMatches } from './glob.match'
2
-
3
- describe('objectMatches', () => {
4
- test('matches a primitive anywhere in the object', () => {
5
- expect(objectMatches({ foo: 'bar' }, 'bar')).toBe(true)
6
- expect(objectMatches({ foo: 11 }, 11)).toBe(true)
7
- expect(objectMatches({ foo: 11 }, 13)).toBe(false)
8
- expect(objectMatches({ foo: 11, bar: 13 }, 13)).toBe(true)
9
- expect(objectMatches({ foo: { bar: 'blue' } }, 'blue')).toBe(true)
10
- expect(objectMatches({ foo: ['bar', 'baz'] }, 'baz')).toBe(true)
11
- expect(objectMatches({ foo: ['bar', 'baz'] }, 'qux')).toBe(false)
12
- })
13
-
14
- test('matches an object', () => {
15
- expect(objectMatches({ foo: 'bar' }, { foo: 'bar' })).toBe(true)
16
- expect(objectMatches({ foo: ['bar', 'baz'] }, { foo: 'bar' })).toBe(true)
17
- })
18
-
19
- test('denies an object with no exact match', () => {
20
- expect(objectMatches({ foo: 'bar' }, { foo: 'bar', baz: 'bar' })).toBe(
21
- false
22
- )
23
- })
24
-
25
- test('accepts an object with one of a match', () => {
26
- expect(objectMatches({ foo: 'bar' }, { foo: ['bar', 'baz'] })).toBe(true)
27
- expect(
28
- objectMatches({ foo: ['bar', 'crux'] }, { foo: ['bar', 'baz'] })
29
- ).toBe(true)
30
- })
31
-
32
- test('accepts an object with wildcard match', () => {
33
- expect(objectMatches({ foo: 'name:bar' }, { foo: 'name:*' })).toBe(true)
34
- expect(objectMatches({ foo: 'name:bar' }, { foo: '*:*' })).toBe(true)
35
- expect(objectMatches({ foo: 'name:bar' }, { foo: '*:bar' })).toBe(true)
36
- expect(objectMatches({ foo: 'name:bar' }, { foo: '**' })).toBe(true)
37
-
38
- expect(
39
- objectMatches({ foo: ['name:bar', 'smth:bar'] }, { foo: 'name:*' })
40
- ).toBe(true)
41
- expect(
42
- objectMatches({ foo: ['name:bar', 'smth:bar'] }, { foo: '*:*' })
43
- ).toBe(true)
44
- expect(
45
- objectMatches({ foo: ['name:bar', 'smth:bar'] }, { foo: '*:bar' })
46
- ).toBe(true)
47
- expect(
48
- objectMatches({ foo: ['name:bar', 'smth:bar'] }, { foo: '**' })
49
- ).toBe(true)
50
- })
51
-
52
- test('denies an object with no wildcard match', () => {
53
- expect(objectMatches({ foo: 'title:bar' }, { foo: 'name:*' })).toBe(false)
54
- expect(objectMatches({ foo: 'name:bar' }, { foo: '*:baz' })).toBe(false)
55
-
56
- expect(
57
- objectMatches({ foo: ['title:bar', 'cool:cat'] }, { foo: 'name:*' })
58
- ).toBe(false)
59
- expect(
60
- objectMatches({ foo: ['name:bar', 'cool:cat'] }, { foo: '*:baz' })
61
- ).toBe(false)
62
- })
63
-
64
- test('accepts an object with one of a wildcard match', () => {
65
- expect(
66
- objectMatches({ foo: 'name:bar' }, { foo: ['name:*', 'title:*'] })
67
- ).toBe(true)
68
- expect(
69
- objectMatches(
70
- { foo: ['name:bar', 'pork:bar'] },
71
- { foo: ['name:*', 'title:*'] }
72
- )
73
- ).toBe(true)
74
- })
75
-
76
- test('denies an object with none of a wildcard match', () => {
77
- expect(
78
- objectMatches({ foo: 'pork:bar' }, { foo: ['name:*', 'title:*'] })
79
- ).toBe(false)
80
- expect(
81
- objectMatches(
82
- { foo: ['pork:bar', 'crinkle:cut'] },
83
- { foo: ['name:*', 'title:*'] }
84
- )
85
- ).toBe(false)
86
- })
87
-
88
- test('allows user to provide a nested match object as well', () => {
89
- expect(
90
- objectMatches({ one: { two: 'bar' } }, { one: { two: 'bar' } })
91
- ).toBe(true)
92
- })
93
-
94
- test('matches a nested key', () => {
95
- expect(objectMatches({ one: { two: 'bar' } }, { 'one.two': 'bar' })).toBe(
96
- true
97
- )
98
- })
99
-
100
- test('does not use end with logic when a nested pattern is provided', () => {
101
- expect(
102
- objectMatches({ zero: { one: { two: 'bar' } } }, { 'one.two': 'bar' })
103
- ).toBe(false)
104
- })
105
-
106
- test('does not use end with logic when a glob pattern is provided', () => {
107
- expect(
108
- objectMatches({ zero: { one: { two: 'bar' } } }, { '*two': 'bar' })
109
- ).toBe(false)
110
- })
111
-
112
- test('matches a glob pattern', () => {
113
- expect(objectMatches({ one: { two: 'bar' } }, { '*.two': 'bar' })).toBe(
114
- true
115
- )
116
- })
117
-
118
- test('defaults to an `endsWith` pattern', () => {
119
- expect(objectMatches({ one: { two: 'bar' } }, { two: 'bar' })).toBe(true)
120
- })
121
-
122
- test('false if non-existent key', () => {
123
- expect(objectMatches({ one: { two: 'bar' } }, { three: 'bar' })).toBe(false)
124
- })
125
-
126
- test('matches a deep glob pattern', () => {
127
- expect(
128
- objectMatches({ one: { two: { three: 'bar' } } }, { '**.three': 'bar' })
129
- ).toBe(true)
130
- expect(
131
- objectMatches({ one: { two: { three: 'bar' } } }, { '*.three': 'bar' })
132
- ).toBe(false)
133
- })
134
-
135
- describe('additional edge cases', () => {
136
- // Empty Objects
137
- test('handles empty objects', () => {
138
- expect(objectMatches({}, {})).toBe(true)
139
- expect(objectMatches({ foo: 'bar' }, {})).toBe(true)
140
- expect(objectMatches({}, { foo: 'bar' })).toBe(false)
141
- })
142
-
143
- // Non-Object Inputs
144
- test('handles non-object inputs', () => {
145
- // @ts-ignore
146
- expect(() => objectMatches('foo', { foo: 'bar' })).toThrow()
147
-
148
- // @ts-ignore
149
- expect(() => objectMatches(123, { foo: 'bar' })).toThrow()
150
-
151
- // @ts-ignore
152
- expect(() => objectMatches(null, { foo: 'bar' })).toThrow()
153
- })
154
-
155
- // Special Characters in Keys
156
- test('handles special characters in keys', () => {
157
- expect(objectMatches({ 'foo*': 'bar' }, { 'foo*': 'bar' })).toBe(true)
158
- expect(objectMatches({ 'foo.bar': 'baz' }, { 'foo.bar': 'baz' })).toBe(
159
- true
160
- )
161
- expect(objectMatches({ foo$bar: 'baz' }, { foo$bar: 'baz' })).toBe(true)
162
- })
163
-
164
- // Matching Null Values
165
- test('matches null values', () => {
166
- expect(objectMatches({ foo: null }, { foo: null })).toBe(true)
167
- expect(objectMatches({ foo: 'bar' }, { foo: null })).toBe(false)
168
- })
169
-
170
- // Matching Undefined Values
171
- test('matches undefined values', () => {
172
- expect(objectMatches({ foo: undefined }, { foo: null })).toBe(true)
173
-
174
- // @ts-ignore
175
- expect(objectMatches({ foo: 'bar' }, { foo: undefined })).toBe(false)
176
- })
177
-
178
- // Nested Array Matches
179
- // test('handles nested array matches', () => {
180
- // expect(
181
- // objectMatches({ foo: [{ bar: 'baz' }] }, { foo: [{ bar: 'baz' }] })
182
- // ).toBe(true)
183
- // expect(
184
- // objectMatches({ foo: [{ bar: 'qux' }] }, { foo: [{ bar: 'baz' }] })
185
- // ).toBe(false)
186
- // })
187
-
188
- // Nested Wildcard Matches
189
- test('handles nested wildcard matches', () => {
190
- expect(
191
- objectMatches({ foo: { bar: 'baz' } }, { foo: { bar: '*' } })
192
- ).toBe(true)
193
- expect(
194
- objectMatches({ foo: { bar: 'qux' } }, { foo: { bar: 'baz*' } })
195
- ).toBe(false)
196
- })
197
-
198
- // Nested Glob Pattern Matches
199
- test('handles nested glob pattern matches', () => {
200
- expect(objectMatches({ foo: { bar: 'baz' } }, { 'foo.*': 'baz' })).toBe(
201
- true
202
- )
203
- expect(objectMatches({ foo: { bar: 'qux' } }, { 'foo.*': 'baz' })).toBe(
204
- false
205
- )
206
- })
207
-
208
- // Type Coercion
209
- test('it attempts to perform type coercion when a string match is provided', () => {
210
- expect(objectMatches({ foo: 1 }, { foo: '1' })).toBe(true)
211
- })
212
-
213
- // Type Coercion
214
- test('it will not coerce types if a non-string matcher is provided', () => {
215
- expect(objectMatches({ foo: '1' }, { foo: 1 })).toBe(false)
216
- })
217
-
218
- // Case Sensitivity
219
- test('is case sensitive', () => {
220
- expect(objectMatches({ foo: 'Bar' }, { foo: 'bar' })).toBe(false)
221
- expect(objectMatches({ foo: 'bar' }, { foo: 'Bar' })).toBe(false)
222
- })
223
-
224
- // Order of Keys
225
- test('does not care about order of keys', () => {
226
- expect(
227
- objectMatches({ foo: 'bar', baz: 'qux' }, { baz: 'qux', foo: 'bar' })
228
- ).toBe(true)
229
- })
230
- })
231
- })
@@ -1,100 +0,0 @@
1
- import { Arrayable } from './event.handler'
2
- import wildMatch from 'wildcard-match'
3
- import flat from 'flat'
4
-
5
- /**
6
- * Glob style matching of a value
7
- *
8
- * @param val
9
- * @param filter
10
- */
11
- export function glob(val: any, filter: string | string[]): boolean {
12
- if (!val || typeof val !== 'string') {
13
- return false
14
- }
15
- return wildMatch(filter || '**', ':')(val)
16
- }
17
-
18
- /**
19
- * Glob style matching of values in an object
20
- *
21
- * @param object
22
- * @param filterObject
23
- */
24
- export function objectMatches(
25
- object: Record<string, any>,
26
- filterObject: JSONPrimitive | FilterObj
27
- ): boolean {
28
- const cleanFilter: FilterObj =
29
- !filterObject || typeof filterObject !== 'object'
30
- ? { '**': filterObject }
31
- : filterObject
32
-
33
- if (typeof object !== 'object') {
34
- throw new Error('You cannot filter a non-object')
35
- }
36
- let denied = false
37
- const filter: FilterObj = flat(cleanFilter, { safe: true })
38
- const flattened = flat(object, { safe: true }) as Record<
39
- string,
40
- JSONPrimitive
41
- >
42
-
43
- // all filters MUST resolve true
44
- for (const keyPattern in filter) {
45
- const keys = filterKeys(flattened, keyPattern)
46
-
47
- const valuePattern = (
48
- Array.isArray(filter[keyPattern])
49
- ? filter[keyPattern]
50
- : [filter[keyPattern]]
51
- ) as JSONPrimitive[]
52
-
53
- // only one filter must match
54
- denied ||= !keys.some((key) => {
55
- const value: JSONPrimitive = flattened[key]
56
- return valuePattern.some((match) => globOrMatch(value, match))
57
- })
58
- }
59
- return !denied
60
- }
61
-
62
- /**
63
- * Glob keys of an object and return the narrowed set
64
- *
65
- * @param object
66
- * @param glob
67
- */
68
- function filterKeys<T extends Record<string, any>>(
69
- object: Record<string, any>,
70
- glob: string
71
- ): Array<keyof T> {
72
- glob = glob.includes('*') || glob.includes('.') ? glob : `**.${glob}`
73
- const matcher = wildMatch(glob, '.')
74
- return Object.keys(object).filter((key) => matcher(key))
75
- }
76
-
77
- function globOrMatch(
78
- val: Arrayable<JSONPrimitive>,
79
- filter: JSONPrimitive
80
- ): boolean {
81
- if (val === undefined || val === null) {
82
- return filter === null
83
- }
84
- if (Array.isArray(val)) {
85
- return val.some((v) => globOrMatch(v, filter))
86
- }
87
- if (typeof filter === 'string') {
88
- return glob(val.toString(), filter)
89
- }
90
-
91
- // otherwise do a simple comparison
92
- return val === filter
93
- }
94
-
95
- type JSONPrimitive = string | number | boolean | null
96
-
97
- type FilterObj = Record<
98
- string,
99
- Arrayable<JSONPrimitive> | Record<string, Arrayable<JSONPrimitive>>
100
- >
@@ -1,3 +0,0 @@
1
- export * from './event.handler'
2
- export * from './flatfile.event'
3
- export * from './authenticated.client'
File without changes
@@ -1,38 +0,0 @@
1
- import { FlatfileListener, FlatfileVirtualMachine } from '../'
2
-
3
- const example = FlatfileListener.create((client) => {
4
- /**
5
- * This is a basic hook on events with no sugar on top
6
- */
7
- client.on('records:*', { target: 'sheet(TestSheet)' }, async (event) => {
8
- const { workbookId, sheetId } = event.context
9
- try {
10
- const records = await event.data
11
- const recordsUpdates = records?.records.map((record: any) => {
12
- record.values.middleName.value = 'TestSheet'
13
-
14
- return record
15
- })
16
- await client.api.updateRecords({
17
- workbookId,
18
- sheetId,
19
- recordsUpdates,
20
- })
21
- } catch (e) {
22
- console.log(`Error getting records: ${e}`)
23
- }
24
- })
25
-
26
- /**
27
- * This is a setup of the space with its workbooks
28
- */
29
- client.on('client:init', async (event) => {
30
- console.log('client:init')
31
- })
32
- })
33
-
34
- const FlatfileVM = new FlatfileVirtualMachine()
35
-
36
- example.mount(FlatfileVM)
37
-
38
- export default example
@@ -1,88 +0,0 @@
1
- import { FlatfileListener } from './flatfile.listener'
2
-
3
- describe('Client', () => {
4
- let testFn: jest.Mock
5
-
6
- beforeEach(() => {
7
- testFn = jest.fn()
8
- })
9
-
10
- describe('triggering', () => {
11
- test('triggers basic event listeners', async () => {
12
- const client = FlatfileListener.create((c) => {
13
- c.on('foo', testFn)
14
- })
15
- await client.dispatchEvent({ topic: 'foo' })
16
- expect(testFn).toHaveBeenCalledTimes(1)
17
- })
18
-
19
- test('triggers namespaced event listeners', () => {
20
- const client = FlatfileListener.create((c) => {
21
- c.on('records:created', testFn)
22
- })
23
- client.dispatchEvent({ topic: 'records:created' })
24
- expect(testFn).toHaveBeenCalled()
25
- })
26
-
27
- test('triggers event listener for array of events', () => {
28
- const client = FlatfileListener.create((c) => {
29
- c.on(['records:created', 'records:updated'], testFn)
30
- })
31
- client.dispatchEvent({ topic: 'records:created' })
32
- client.dispatchEvent({ topic: 'records:updated' })
33
- expect(testFn).toHaveBeenCalledTimes(2)
34
- })
35
-
36
- test('triggers event listener for wildcard query of events', () => {
37
- const client = FlatfileListener.create((c) => {
38
- c.on('records:*', testFn)
39
- })
40
- client.dispatchEvent({ topic: 'records:created' })
41
- client.dispatchEvent({ topic: 'records:updated' })
42
- client.dispatchEvent({ topic: 'records:deleted' })
43
- expect(testFn).toHaveBeenCalledTimes(3)
44
- })
45
- })
46
-
47
- describe('filtering', () => {
48
- test('trigger only when filter match - on listener', async () => {
49
- const client = FlatfileListener.create((c) => {
50
- c.on('records:created', { domain: 'foo' }, testFn)
51
- })
52
- await client.dispatchEvent({ topic: 'records:created' })
53
- await client.dispatchEvent({ topic: 'records:created', domain: 'foo' })
54
- expect(testFn).toHaveBeenCalledTimes(1)
55
- })
56
-
57
- test('trigger only when filter match - on scope', async () => {
58
- const client = FlatfileListener.create((c) => {
59
- c.filter({ domain: 'foo' }, (f) => {
60
- f.on('records:created', testFn)
61
- })
62
- })
63
- await client.dispatchEvent({ topic: 'records:created' })
64
- await client.dispatchEvent({ topic: 'records:created', domain: 'foo' })
65
- expect(testFn).toHaveBeenCalledTimes(1)
66
- })
67
-
68
- test('multiple layers of filtering', async () => {
69
- const client = FlatfileListener.create((c) => {
70
- c.filter({ domain: 'foo:*' })
71
- .filter({ domain: 'foo:bar' })
72
- .use((f) => {
73
- f.on('records:created', testFn)
74
- })
75
- })
76
- await client.dispatchEvent({ topic: 'records:created' })
77
- await client.dispatchEvent({
78
- topic: 'records:created',
79
- domain: 'foo:bar',
80
- })
81
- await client.dispatchEvent({
82
- topic: 'records:created',
83
- domain: 'foo:baz',
84
- })
85
- expect(testFn).toHaveBeenCalledTimes(1)
86
- })
87
- })
88
- })
@@ -1,78 +0,0 @@
1
- /**
2
- * The Flatfile Listener
3
- *
4
- * The Flatfile PubSub Client is just a simple event subscriber. It can
5
- * receive events from any PubSub driver. The default drivers are:
6
- *
7
- * - Webhook (for simply processing events sent to URL)
8
- * - Websocket (for subscribing real time on an HTTP2 connection)
9
- * - Serverless (for stateless invocations via AWS Lambda or similar)
10
- *
11
- * Once an event is received, it is routed to any awaiting listeners which
12
- * are added with `addEventListener()` or its alias `on()`.
13
- *
14
- * Flatfile events follow a standard structure and event listeners can use
15
- * any of the following syntaxes to react to events within Flatfile.
16
- *
17
- * // listen to an event
18
- * addEventListener('entity:topic')
19
- *
20
- * // listen to an event on a specific namespace
21
- * addEventListener('entity:topic@namespace')
22
- *
23
- * // listen to a specific context on a namespace
24
- * addEventListener('entity:topic@namespace?context=us_sp_89234oihsdo')
25
- *
26
- * // filter by any
27
- * addEventListener('entity:topic@namespace?')
28
- *
29
- */
30
-
31
- import { EventFilter, EventHandler } from './events'
32
- import { EventDriver } from './event-drivers/_EventDriver'
33
-
34
- export class FlatfileListener extends EventHandler {
35
- /**
36
- * Subscribe to events only within a certain namespace.
37
- *
38
- * @param namespace
39
- * @param cb
40
- */
41
- namespace(namespace: string | string[], cb?: SubFn) {
42
- return this.filter({ namespace }, cb)
43
- }
44
-
45
- /**
46
- * Filter by namespace
47
- *
48
- * @param filter
49
- * @param cb
50
- */
51
- filter(filter: EventFilter, cb?: SubFn) {
52
- const client = new FlatfileListener(filter)
53
- this.addNode(client)
54
- cb?.(client)
55
- return client
56
- }
57
-
58
- /**
59
- * Start subscribing to events
60
- *
61
- * @param cb
62
- */
63
- public static create(cb: SubFn): FlatfileListener {
64
- const client = new FlatfileListener()
65
- cb(client)
66
- return client
67
- }
68
-
69
- /**
70
- * Mount this client using an acceptable Event Driver
71
- */
72
- mount(driver: EventDriver) {
73
- driver.mountEventHandler(this)
74
- return this
75
- }
76
- }
77
-
78
- type SubFn = (client: FlatfileListener) => void
package/src/index.ts DELETED
@@ -1,9 +0,0 @@
1
- import { FlatfileListener } from './flatfile.listener'
2
- export * from './flatfile.listener'
3
- export * from './event-drivers'
4
- export * from './events'
5
-
6
- /**
7
- * Backwards compatibility
8
- */
9
- export class Client extends FlatfileListener {}
@@ -1 +0,0 @@
1
- // export * from './useConfigure'
@@ -1,72 +0,0 @@
1
- // import { Client } from '../Client'
2
- // import { Blueprint } from '@flatfile/api'
3
- // import { Agent } from '@flatfile/configure'
4
-
5
- // type IConfigureOptions = { environmentId?: string; createSpaces?: boolean }
6
-
7
- // // TODO: first pass at useConfigure Plugin. Does not register hooks, only deploys the spaceConfig
8
- // export const useConfigure = (agent: Agent, options?: IConfigureOptions) => {
9
- // const configure = async (client: Client) => {
10
- // const {
11
- // options: { spaceConfigs },
12
- // } = agent
13
- // for (const slug in spaceConfigs) {
14
- // const spaceConfig = spaceConfigs[slug]
15
-
16
- // try {
17
- // const spacePatternConfig = {
18
- // name: spaceConfig.options.name,
19
- // // TODO Do we need a unique slug for this in the Platform SDK or X? Should we generate them in X?
20
- // slug,
21
- // blueprints: mapObj(
22
- // spaceConfig.options.workbookConfigs,
23
- // (wb, wbSlug, i) => {
24
- // return {
25
- // name: wb.options.name,
26
- // slug: `${slug}/${wbSlug}`,
27
- // primary: i === 0,
28
- // sheets: mapObj(wb.options.sheets, (model, modelSlug) =>
29
- // model.toBlueprint(wbSlug, modelSlug)
30
- // ),
31
- // } as Blueprint
32
- // }
33
- // ),
34
- // }
35
- // const spaceConfigRes = await client.api.addSpaceConfig({
36
- // spacePatternConfig,
37
- // })
38
-
39
- // const spaceConfigId = spaceConfigRes?.data?.id || ''
40
-
41
- // if (options?.createSpaces && options.environmentId) {
42
- // try {
43
- // const space = await client.api.addSpace({
44
- // spaceConfig: {
45
- // spaceConfigId,
46
- // environmentId: options.environmentId,
47
- // name: spaceConfig.options.name,
48
- // },
49
- // })
50
- // } catch (e) {
51
- // console.log(`Error Creating Space error: ${e}`)
52
- // }
53
- // }
54
- // } catch (e) {
55
- // console.log(`Error Creating Space Config: ${e}`)
56
- // }
57
- // }
58
- // }
59
- // return configure
60
- // }
61
-
62
- // function mapObj<T, K>(
63
- // obj: Record<string, K>,
64
- // cb: (value: K, key: string, i: number) => T
65
- // ): T[] {
66
- // const slugs = Object.keys(obj)
67
- // let i = 0
68
- // return slugs.map((slug) => {
69
- // const model = obj[slug]
70
- // return cb(model, slug, i++)
71
- // })
72
- // }
package/tsconfig.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "extends": "@flatfile/ts-config-platform-sdk/base.json",
3
- "include": ["./src"],
4
- "exclude": ["dist", "build", "node_modules"],
5
- "compilerOptions": {
6
- "lib": ["ESNext"],
7
- "module": "ESNext",
8
- "target": "es2020"
9
- },
10
- }