summaryrefslogtreecommitdiff
path: root/src/jet/jet.ts
blob: 75b0afce0c06336921b402131f7af26396eae8fa (plain)
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
import type I18N from '@amp/web-apps-localization';
import type { Logger, LoggerFactory } from '@amp/web-apps-logger';

import type { AppStoreObjectGraph } from '@jet-app/app-store/foundation/runtime/app-store-object-graph';
import type { AppStoreRuntime } from '@jet-app/app-store/foundation/runtime/runtime';
import type {
    NormalizedStorefront,
    NormalizedLanguage,
} from '@jet-app/app-store/api/locale';

import type {
    LintedMetricsEvent,
    MetricsFields,
    PageMetrics,
} from '@jet/environment/types/metrics';
import { type Opt } from '@jet/environment/types/optional';
import type { Intent, IntentReturnType } from '@jet/environment/dispatching';
import {
    type ActionImplementation,
    ActionDispatcher,
    type ActionOutcome,
    type MetricsBehavior,
} from '@jet/engine';

import { Metrics } from '@amp/web-apps-metrics-8';
import { makeMetricsSettings } from '~/jet/metrics/settings';
import { makeMetricsProviders } from '~/jet/metrics/providers';
import { config as metricsConfig } from '~/config/metrics';

import { bootstrap } from '~/jet/bootstrap';
import { makeDependencies } from '~/jet/dependencies';
import type { Locale } from '~/jet/dependencies/locale';
import type { WebLocalization } from '~/jet/dependencies/localization';
import {
    type RouterResponse,
    type RouteUrlIntent,
    makeRouteUrlIntent,
    makeLintMetricsEventIntent,
} from '~/jet/intents';
import type { Page, ActionModel } from '~/jet/models';
import { PrefetchedIntents } from '@amp/web-apps-common/src/jet/prefetched-intents';
import { CONTEXT_NAME } from '~/jet/svelte';
import type { FeaturesCallbacks } from './dependencies/net';

/**
 * The entry point for interacting with the Jet shared business logic.
 */
export class Jet {
    private readonly log: Logger;
    private readonly runtime: AppStoreRuntime;
    private readonly actionDispatcher: ActionDispatcher;
    private readonly metrics: Metrics;
    private readonly locale: Locale;

    /**
     * Intents (and their resolved data) that have yet to be dispatched that
     * were recently dispatched. These are consulted before dispatching
     * intents. If a prefetched intent exists for an ongoing dispatch, it will
     * be used as the return value instead of actually dispatching.
     *
     * This can be used, for example, for intents that are dispatched during
     * SSR. The server can serialize the intents it dispatches and then the
     * client can populate this, to avoid re-dispatching the intents.
     */
    private readonly prefetchedIntents: PrefetchedIntents;

    /**
     * A set of the action types that already have registered implementations to catch
     * double registers.
     */
    private readonly wiredActions: Set<string>;

    readonly objectGraph: AppStoreObjectGraph;
    readonly localization: WebLocalization;

    static load({
        loggerFactory,
        context,
        fetch,
        prefetchedIntents = PrefetchedIntents.empty(),
        featuresCallbacks,
    }: {
        loggerFactory: LoggerFactory;
        context: Map<string, unknown>;
        fetch: typeof window.fetch;
        prefetchedIntents?: PrefetchedIntents;
        featuresCallbacks?: FeaturesCallbacks;
    }): Jet {
        const dependencies = makeDependencies(
            loggerFactory,
            fetch,
            featuresCallbacks,
        );
        const { runtime, objectGraph } = bootstrap(dependencies);
        let jet: Jet;

        const processEvent = async (
            fields: MetricsFields,
        ): Promise<LintedMetricsEvent> => {
            const intent = makeLintMetricsEventIntent({ fields });
            return jet.dispatch(intent);
        };
        const metrics = Metrics.load(
            loggerFactory,
            context,
            processEvent,
            metricsConfig,
            makeMetricsProviders(objectGraph),
            makeMetricsSettings(context),
        );
        const actionDispatcher = new ActionDispatcher(
            // `@amp/web-apps-metrics` depends on a different version of `@jet/engine` with a different
            // type definition for `MetricsPipeline`
            // @ts-expect-error
            metrics.metricsPipeline,
        );

        jet = new Jet(
            loggerFactory.loggerFor('Jet'),
            runtime,
            objectGraph,
            actionDispatcher,
            metrics,
            dependencies.locale,
            prefetchedIntents,
            dependencies.localization,
        );

        context.set(CONTEXT_NAME, jet);

        return jet;
    }

    private constructor(
        log: Logger,
        runtime: AppStoreRuntime,
        objectGraph: AppStoreObjectGraph,
        actionDispatcher: ActionDispatcher,
        metrics: Metrics,
        locale: Locale,
        prefetchedIntents: PrefetchedIntents,
        localization: WebLocalization,
    ) {
        this.log = log;
        this.runtime = runtime;
        this.objectGraph = objectGraph;
        this.actionDispatcher = actionDispatcher;

        this.metrics = metrics;
        this.locale = locale;
        this.localization = localization;

        this.prefetchedIntents = prefetchedIntents;

        this.wiredActions = new Set();
    }

    async didEnterPage(page: Page | null): Promise<void> {
        // This is a very temporary hacky fix to move the `platformContext` value from
        // `pageRenderFields` to `pageFields`, which will eventually happen in the Jet
        // business logic.
        const pageWithMetrics = { ...page };
        if (pageWithMetrics.pageMetrics?.pageFields) {
            pageWithMetrics.pageMetrics.pageFields.platformContext =
                pageWithMetrics.pageMetrics.pageRenderFields?.platformContext;
        }

        // @ts-expect-error - pageMetrics property not required at runtime
        await this.metrics.didEnterPage(page);
    }

    get pageMetrics(): Opt<PageMetrics> {
        return this.metrics.currentPageMetrics?.pageMetrics;
    }

    /**
     * Dispatch a Jet intent, returning its output.
     *
     * @param intent The intent to dispatch
     * @return output The value returned by the intent's controller
     */
    async dispatch<I extends Intent<unknown>>(
        intent: I,
    ): Promise<IntentReturnType<I>> {
        const data = this.prefetchedIntents.get(intent);
        if (data) {
            this.log.info(
                're-using prefetched intent response for:',
                intent,
                'data:',
                data,
            );
            return data;
        }

        // TODO: rdar://73165545 (Error Handling Across App)
        return this.runtime.dispatch(intent);
    }

    /**
     * Perform a Jet action, returning the outcome.
     *
     * @param action The action to perform
     * @param metricsBehavior Indicates how to handle metrics for this action
     * @return outcome Either 'performed' or 'unsupported'
     */
    async perform(
        action: ActionModel,
        metricsBehavior?: MetricsBehavior,
    ): Promise<ActionOutcome> {
        if (!metricsBehavior) {
            if (this.pageMetrics) {
                metricsBehavior = {
                    behavior: 'fromAction',
                    context: this.pageMetrics || {},
                };
            } else {
                this.log.warn(
                    'No pageMetrics found for jet.perform action:',
                    action,
                );
                metricsBehavior = { behavior: 'notProcessed' };
            }
        }
        // TODO: rdar://73165545 (Error Handling Across App): handle throw
        const outcome = await this.actionDispatcher.perform(
            action,
            metricsBehavior,
        );

        if (outcome === 'unsupported') {
            this.log.error(
                'unable to perform action:',
                action,
                metricsBehavior,
            );
        }

        return outcome;
    }

    /**
     * Register an implementation to handle a Jet action.
     *
     * @param kind The type of the action
     * @param implementation The code to run when that action is performed
     */
    onAction<A extends ActionModel>(
        kind: string,
        implementation: ActionImplementation<A>,
    ): void {
        if (this.wiredActions.has(kind)) {
            throw new Error(
                `onAction called twice with the same action type: ${kind}`,
            );
        }

        this.actionDispatcher.register(kind, implementation);
        this.wiredActions.add(kind);
    }

    /**
     * Route a URL using Jet, returning the routing if the URL could be routed.
     *
     * @param url The URL to route
     * @return routing The routing of the URL or null if unrouteable
     */
    async routeUrl(url: string): Promise<RouterResponse | null> {
        // TODO: rdar://73165545 (Error Handling Across App): what about 404s?
        const routerResponse = await this.dispatch<RouteUrlIntent>(
            makeRouteUrlIntent({ url }),
        );

        if (routerResponse && routerResponse.action) {
            return routerResponse;
        }

        this.log.warn(
            'url did not resolve to a flow action with a discernable intent:',
            url,
            routerResponse,
        );

        return null;
    }

    /**
     * Propagates the routing-derrived localization information through the Jet app
     *
     * The {@link Locale} instance that is configured here is referenced by
     * the rest of our Jet dependencies in order to lazily retreive the locale
     * information.
     *
     * @param localizer
     * @param storefront
     * @param language
     */
    setLocale(
        localizer: I18N,
        storefront: NormalizedStorefront,
        language: NormalizedLanguage,
    ): void {
        this.locale.i18n = localizer;
        this.locale.setActiveLocale({ storefront, language });
    }

    recordCustomMetricsEvent(fields?: Opt<MetricsFields>) {
        this.metrics.recordCustomEvent(fields);
    }

    enableFunnelKit(): void {
        this.metrics.enableFunnelKit();
    }

    disableFunnelKit(): void {
        this.metrics.disableFunnelKit();
    }

    // TODO: rdar://75011660 (Bridge Jet to MetricsKit and PerfKit for reporting)
}