-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathindex.ts
More file actions
324 lines (276 loc) · 8.99 KB
/
index.ts
File metadata and controls
324 lines (276 loc) · 8.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { CDNSettings } from '../../browser'
import { JSONObject, JSONValue } from '../../core/events'
import { Plugin, InternalPluginWithAddMiddleware } from '../../core/plugin'
import { loadScript } from '../../lib/load-script'
import { getCDN } from '../../lib/parse-cdn'
import {
applyDestinationMiddleware,
DestinationMiddlewareFunction,
} from '../middleware'
import { Context, ContextCancelation } from '../../core/context'
import { recordIntegrationMetric } from '../../core/stats/metric-helpers'
import { Analytics, InitOptions } from '../../core/analytics'
import { createDeferred } from '@segment/analytics-generic-utils'
import { IntegrationsInitOptions } from '../../browser/settings'
export interface RemotePlugin {
/** The name of the remote plugin */
name: string
/** The creation name of the remote plugin */
creationName: string
/** The url of the javascript file to load */
url: string
/** The UMD/global name the plugin uses. Plugins are expected to exist here with the `PluginFactory` method signature */
libraryName: string
/** The settings related to this plugin. */
settings: JSONObject
}
export class ActionDestination implements InternalPluginWithAddMiddleware {
name: string // destination name
version = '1.0.0'
/**
* The lifecycle name of the wrapped plugin.
* This does not need to be 'destination', and can be 'enrichment', etc.
*/
type: Plugin['type']
alternativeNames: string[] = []
private loadPromise = createDeferred<unknown>()
middleware: DestinationMiddlewareFunction[] = []
action: Plugin
constructor(name: string, action: Plugin) {
this.action = action
this.name = name
this.type = action.type
this.alternativeNames.push(action.name)
}
addMiddleware(...fn: DestinationMiddlewareFunction[]): void {
/** Make sure we only apply destination filters to actions of the "destination" type to avoid causing issues for hybrid destinations */
if (this.type === 'destination') {
this.middleware.push(...fn)
}
}
private async transform(ctx: Context): Promise<Context> {
const modifiedEvent = await applyDestinationMiddleware(
this.name,
ctx.event,
this.middleware
)
if (modifiedEvent === null) {
ctx.cancel(
new ContextCancelation({
retry: false,
reason: 'dropped by destination middleware',
})
)
}
return new Context(modifiedEvent!)
}
private _createMethod(
methodName: 'track' | 'page' | 'identify' | 'alias' | 'group' | 'screen'
) {
return async (ctx: Context): Promise<Context> => {
if (!this.action[methodName]) return ctx
let transformedContext: Context = ctx
// Transformations only allowed for destination plugins. Other plugin types support mutating events.
if (this.type === 'destination') {
transformedContext = await this.transform(ctx)
}
try {
if (!(await this.ready())) {
throw new Error(
'Something prevented the destination from getting ready'
)
}
recordIntegrationMetric(ctx, {
integrationName: this.action.name,
methodName,
type: 'action',
})
await this.action[methodName]!(transformedContext)
} catch (error) {
recordIntegrationMetric(ctx, {
integrationName: this.action.name,
methodName,
type: 'action',
didError: true,
})
throw error
}
return ctx
}
}
alias = this._createMethod('alias')
group = this._createMethod('group')
identify = this._createMethod('identify')
page = this._createMethod('page')
screen = this._createMethod('screen')
track = this._createMethod('track')
/* --- PASSTHROUGH METHODS --- */
isLoaded(): boolean {
return this.action.isLoaded()
}
async ready(): Promise<boolean> {
try {
await this.loadPromise.promise
return true
} catch {
return false
}
}
async load(ctx: Context, analytics: Analytics): Promise<unknown> {
if (this.loadPromise.isSettled()) {
return this.loadPromise.promise
}
try {
recordIntegrationMetric(ctx, {
integrationName: this.action.name,
methodName: 'load',
type: 'action',
})
const loadP = this.action.load(ctx, analytics)
this.loadPromise.resolve(await loadP)
return loadP
} catch (error) {
recordIntegrationMetric(ctx, {
integrationName: this.action.name,
methodName: 'load',
type: 'action',
didError: true,
})
this.loadPromise.reject(error)
throw error
}
}
unload(ctx: Context, analytics: Analytics): Promise<unknown> | unknown {
return this.action.unload?.(ctx, analytics)
}
}
export type PluginFactory = {
(settings: JSONValue): Plugin | Plugin[] | Promise<Plugin | Plugin[]>
pluginName: string
}
function validate(pluginLike: unknown): pluginLike is Plugin[] {
if (!Array.isArray(pluginLike)) {
throw new Error('Not a valid list of plugins')
}
const required = ['load', 'isLoaded', 'name', 'version', 'type']
pluginLike.forEach((plugin) => {
required.forEach((method) => {
if (plugin[method] === undefined) {
throw new Error(
`Plugin: ${
plugin.name ?? 'unknown'
} missing required function ${method}`
)
}
})
})
return true
}
function isPluginDisabled(
userIntegrations: IntegrationsInitOptions,
remotePlugin: RemotePlugin
) {
const creationNameEnabled = userIntegrations[remotePlugin.creationName]
const currentNameEnabled = userIntegrations[remotePlugin.name]
// Check that the plugin isn't explicitly enabled when All: false
if (
userIntegrations.All === false &&
!creationNameEnabled &&
!currentNameEnabled
) {
return true
}
// Check that the plugin isn't explicitly disabled
if (creationNameEnabled === false || currentNameEnabled === false) {
return true
}
return false
}
async function loadPluginFactory(
remotePlugin: RemotePlugin,
obfuscate?: boolean
): Promise<void | PluginFactory> {
try {
const defaultCdn = new RegExp('https://cdn.segment.(com|build)')
const cdn = getCDN()
if (obfuscate) {
const urlSplit = remotePlugin.url.split('/')
const name = urlSplit[urlSplit.length - 2]
const obfuscatedURL = remotePlugin.url.replace(
name,
btoa(name).replace(/=/g, '')
)
try {
await loadScript(obfuscatedURL.replace(defaultCdn, cdn))
} catch (error) {
// Due to syncing concerns it is possible that the obfuscated action destination (or requested version) might not exist.
// We should use the unobfuscated version as a fallback.
await loadScript(remotePlugin.url.replace(defaultCdn, cdn))
}
} else {
await loadScript(remotePlugin.url.replace(defaultCdn, cdn))
}
// @ts-expect-error
if (typeof window[remotePlugin.libraryName] === 'function') {
// @ts-expect-error
return window[remotePlugin.libraryName] as PluginFactory
}
} catch (err) {
console.error('Failed to create PluginFactory', remotePlugin)
throw err
}
}
export async function remoteLoader(
settings: CDNSettings,
integrations: IntegrationsInitOptions,
mergedIntegrations: Record<string, JSONObject>,
options?: InitOptions,
routingMiddleware?: DestinationMiddlewareFunction,
pluginSources?: PluginFactory[]
): Promise<Plugin[]> {
const allPlugins: Plugin[] = []
const routingRules = settings.middlewareSettings?.routingRules ?? []
const pluginPromises = (settings.remotePlugins ?? []).map(
async (remotePlugin) => {
if (isPluginDisabled(integrations, remotePlugin)) return
try {
const pluginFactory =
pluginSources?.find(
({ pluginName }) => pluginName === remotePlugin.name
) || (await loadPluginFactory(remotePlugin, options?.obfuscate))
if (pluginFactory) {
const intg = mergedIntegrations[remotePlugin.name]
const plugin = await pluginFactory({
...remotePlugin.settings,
...intg,
})
const plugins = Array.isArray(plugin) ? plugin : [plugin]
validate(plugins)
const routing = routingRules.filter(
(rule) => rule.destinationName === remotePlugin.creationName
)
plugins.forEach((plugin) => {
const wrapper = new ActionDestination(
remotePlugin.creationName,
plugin
)
if (routing.length && routingMiddleware) {
wrapper.addMiddleware(routingMiddleware)
}
allPlugins.push(wrapper)
})
}
} catch (error) {
console.warn('Failed to load Remote Plugin', error)
recordIntegrationMetric(Context.system(), {
integrationName: remotePlugin.name,
methodName: 'load',
type: 'action',
didError: true,
})
}
}
)
await Promise.all(pluginPromises)
return allPlugins.filter(Boolean)
}