@croct/plug 0.16.5 → 0.17.1

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.
Files changed (116) hide show
  1. package/api/evaluate.cjs +45 -0
  2. package/api/evaluate.d.cts +23 -0
  3. package/api/evaluate.d.ts +9 -7
  4. package/api/evaluate.js +20 -22
  5. package/api/fetchContent.cjs +55 -0
  6. package/api/fetchContent.d.cts +45 -0
  7. package/api/fetchContent.d.ts +31 -11
  8. package/api/fetchContent.js +31 -21
  9. package/api/index.cjs +23 -0
  10. package/api/index.d.cts +27 -0
  11. package/api/index.d.ts +27 -2
  12. package/api/index.js +2 -6
  13. package/component.cjs +15 -0
  14. package/component.d.cts +19 -0
  15. package/component.d.ts +12 -9
  16. package/component.js +0 -3
  17. package/constants.cjs +39 -0
  18. package/constants.d.cts +7 -0
  19. package/constants.d.ts +7 -5
  20. package/constants.js +12 -9
  21. package/index.cjs +24 -0
  22. package/index.d.cts +27 -0
  23. package/index.d.ts +26 -3
  24. package/index.js +5 -6
  25. package/package.json +34 -7
  26. package/playground.cjs +166 -0
  27. package/playground.d.cts +64 -0
  28. package/playground.d.ts +18 -8
  29. package/playground.js +130 -138
  30. package/plug.cjs +279 -0
  31. package/plug.d.cts +86 -0
  32. package/plug.d.ts +34 -17
  33. package/plug.js +239 -244
  34. package/plugin.cjs +15 -0
  35. package/plugin.d.cts +41 -0
  36. package/plugin.d.ts +18 -8
  37. package/plugin.js +0 -3
  38. package/preview.cjs +180 -0
  39. package/preview.d.cts +35 -0
  40. package/preview.d.ts +18 -6
  41. package/preview.js +143 -152
  42. package/sdk/apiKey.cjs +21 -0
  43. package/sdk/apiKey.js +1 -5
  44. package/sdk/evaluation.cjs +34 -0
  45. package/sdk/evaluation.d.cts +2 -0
  46. package/sdk/evaluation.d.ts +1 -1
  47. package/sdk/evaluation.js +8 -10
  48. package/sdk/index.cjs +33 -0
  49. package/sdk/index.d.cts +15 -0
  50. package/sdk/index.d.ts +9 -6
  51. package/sdk/index.js +8 -10
  52. package/sdk/json.cjs +15 -0
  53. package/sdk/json.d.cts +6 -0
  54. package/sdk/json.d.ts +4 -1
  55. package/sdk/json.js +0 -5
  56. package/sdk/sdkEvents.cjs +15 -0
  57. package/sdk/sdkEvents.d.cts +1 -0
  58. package/sdk/sdkEvents.js +0 -3
  59. package/sdk/token.cjs +27 -0
  60. package/sdk/token.d.cts +7 -0
  61. package/sdk/token.d.ts +7 -1
  62. package/sdk/token.js +4 -6
  63. package/sdk/tracking.cjs +27 -0
  64. package/sdk/tracking.d.cts +9 -0
  65. package/sdk/tracking.d.ts +8 -5
  66. package/sdk/tracking.js +4 -6
  67. package/sdk/validation.cjs +23 -0
  68. package/sdk/validation.js +2 -6
  69. package/slot.cjs +15 -0
  70. package/slot.d.cts +42 -0
  71. package/slot.d.ts +14 -12
  72. package/slot.js +0 -3
  73. package/versioning.cjs +15 -0
  74. package/versioning.d.cts +26 -0
  75. package/versioning.d.ts +8 -6
  76. package/versioning.js +0 -3
  77. package/api/evaluate.js.map +0 -1
  78. package/api/fetchContent.js.map +0 -1
  79. package/api/index.js.map +0 -1
  80. package/component.js.map +0 -1
  81. package/constants.js.map +0 -1
  82. package/index.js.map +0 -1
  83. package/playground.js.map +0 -1
  84. package/plug.js.map +0 -1
  85. package/plugin.js.map +0 -1
  86. package/preview.js.map +0 -1
  87. package/sdk/apiKey.js.map +0 -1
  88. package/sdk/evaluation.js.map +0 -1
  89. package/sdk/index.js.map +0 -1
  90. package/sdk/json.js.map +0 -1
  91. package/sdk/sdkEvents.js.map +0 -1
  92. package/sdk/token.js.map +0 -1
  93. package/sdk/tracking.js.map +0 -1
  94. package/sdk/validation.js.map +0 -1
  95. package/slot.js.map +0 -1
  96. package/src/api/evaluate.ts +0 -50
  97. package/src/api/fetchContent.ts +0 -70
  98. package/src/api/index.ts +0 -2
  99. package/src/component.ts +0 -19
  100. package/src/constants.ts +0 -5
  101. package/src/index.ts +0 -6
  102. package/src/playground.ts +0 -247
  103. package/src/plug.ts +0 -429
  104. package/src/plugin.ts +0 -39
  105. package/src/preview.ts +0 -226
  106. package/src/sdk/evaluation.ts +0 -2
  107. package/src/sdk/index.ts +0 -14
  108. package/src/sdk/json.ts +0 -4
  109. package/src/sdk/sdkEvents.ts +0 -1
  110. package/src/sdk/token.ts +0 -1
  111. package/src/sdk/tracking.ts +0 -14
  112. package/src/slot.ts +0 -48
  113. package/src/versioning.ts +0 -38
  114. package/versioning.js.map +0 -1
  115. /package/{src/sdk/apiKey.ts → sdk/apiKey.d.cts} +0 -0
  116. /package/{src/sdk/validation.ts → sdk/validation.d.cts} +0 -0
package/plug.d.ts CHANGED
@@ -2,24 +2,37 @@ import { SessionFacade } from '@croct/sdk/facade/sessionFacade';
2
2
  import { UserFacade } from '@croct/sdk/facade/userFacade';
3
3
  import { TrackerFacade } from '@croct/sdk/facade/trackerFacade';
4
4
  import { EvaluationOptions, EvaluatorFacade } from '@croct/sdk/facade/evaluatorFacade';
5
- import { Configuration as SdkFacadeConfiguration } from '@croct/sdk/facade/sdkFacade';
5
+ import { Configuration as Configuration$1 } from '@croct/sdk/facade/sdkFacade';
6
6
  import { Optional } from '@croct/sdk/utilityTypes';
7
- import { ExternalTrackingEvent as ExternalEvent, ExternalTrackingEventPayload as ExternalEventPayload, ExternalTrackingEventType as ExternalEventType } from '@croct/sdk/trackingEvents';
8
- import { FetchOptions as BaseFetchOptions } from '@croct/sdk/facade/contentFetcherFacade';
9
- import { PluginFactory } from './plugin';
10
- import { VersionedSlotId, SlotContent } from './slot';
11
- import { JsonValue, JsonObject } from './sdk/json';
12
- export interface PluginConfigurations {
7
+ import { ExternalTrackingEventType, ExternalTrackingEventPayload, ExternalTrackingEvent } from '@croct/sdk/trackingEvents';
8
+ import { FetchOptions as FetchOptions$1 } from '@croct/sdk/facade/contentFetcherFacade';
9
+ import { PluginFactory } from './plugin.js';
10
+ import { VersionedSlotId, SlotContent } from './slot.js';
11
+ import { JsonValue, JsonObject } from '@croct/json/mutable';
12
+ import '@croct/sdk/token';
13
+ import './sdk/index.js';
14
+ import '@croct/sdk/eventManager';
15
+ import '@croct/sdk/sdkEvents';
16
+ import '@croct/sdk/logging';
17
+ import '@croct/sdk/tab';
18
+ import '@croct/sdk/cid';
19
+ import '@croct/json';
20
+ import './versioning.js';
21
+ import './component.js';
22
+
23
+ interface PluginConfigurations {
13
24
  [key: string]: any;
14
25
  }
15
- export type Configuration = Optional<SdkFacadeConfiguration, 'appId'> & {
26
+ type Configuration = Optional<Configuration$1, 'appId'> & {
16
27
  plugins?: PluginConfigurations;
17
28
  };
18
- export type FetchOptions = Omit<BaseFetchOptions, 'version'>;
19
- export type FetchResponse<I extends VersionedSlotId, C extends JsonObject = JsonObject> = {
20
- content: SlotContent<I, C>;
29
+ type FetchOptions<T> = Omit<FetchOptions$1, 'version'> & {
30
+ fallback?: T;
21
31
  };
22
- export interface Plug {
32
+ type FetchResponse<I extends VersionedSlotId, C extends JsonObject = JsonObject, F = never> = {
33
+ content: SlotContent<I, C> | F;
34
+ };
35
+ interface Plug {
23
36
  readonly tracker: TrackerFacade;
24
37
  readonly user: UserFacade;
25
38
  readonly session: SessionFacade;
@@ -33,12 +46,13 @@ export interface Plug {
33
46
  anonymize(): void;
34
47
  setToken(token: string): void;
35
48
  unsetToken(): void;
36
- track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;
49
+ track<T extends ExternalTrackingEventType>(type: T, payload: ExternalTrackingEventPayload<T>): Promise<ExternalTrackingEvent<T>>;
37
50
  evaluate<T extends JsonValue>(expression: string, options?: EvaluationOptions): Promise<T>;
38
- fetch<P extends JsonObject, I extends VersionedSlotId>(slotId: I, options?: FetchOptions): Promise<FetchResponse<I, P>>;
51
+ fetch<I extends VersionedSlotId>(slotId: I, options?: FetchOptions<SlotContent<I>>): Promise<FetchResponse<I>>;
52
+ fetch<F, I extends VersionedSlotId>(slotId: I, options?: FetchOptions<SlotContent<I> | F>): Promise<FetchResponse<I, JsonObject, F>>;
39
53
  unplug(): Promise<void>;
40
54
  }
41
- export declare class GlobalPlug implements Plug {
55
+ declare class GlobalPlug implements Plug {
42
56
  private pluginFactories;
43
57
  private instance?;
44
58
  private plugins;
@@ -61,9 +75,12 @@ export declare class GlobalPlug implements Plug {
61
75
  anonymize(): void;
62
76
  setToken(token: string): void;
63
77
  unsetToken(): void;
64
- track<T extends ExternalEventType>(type: T, payload: ExternalEventPayload<T>): Promise<ExternalEvent<T>>;
78
+ track<T extends ExternalTrackingEventType>(type: T, payload: ExternalTrackingEventPayload<T>): Promise<ExternalTrackingEvent<T>>;
65
79
  evaluate<T extends JsonValue>(query: string, options?: EvaluationOptions): Promise<T>;
66
80
  test(expression: string, options?: EvaluationOptions): Promise<boolean>;
67
- fetch<C extends JsonObject, I extends VersionedSlotId = VersionedSlotId>(slotId: I, options?: FetchOptions): Promise<FetchResponse<I, C>>;
81
+ fetch<I extends VersionedSlotId>(slotId: I, options?: FetchOptions<SlotContent<I>>): Promise<FetchResponse<I>>;
82
+ fetch<F, I extends VersionedSlotId>(slotId: I, options?: FetchOptions<SlotContent<I> | F>): Promise<FetchResponse<I, JsonObject, F>>;
68
83
  unplug(): Promise<void>;
69
84
  }
85
+
86
+ export { type Configuration, type FetchOptions, type FetchResponse, GlobalPlug, type Plug, type PluginConfigurations };
package/plug.js CHANGED
@@ -1,261 +1,256 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GlobalPlug = void 0;
4
- const sdkFacade_1 = require("@croct/sdk/facade/sdkFacade");
5
- const error_1 = require("@croct/sdk/error");
6
- const validation_1 = require("@croct/sdk/validation");
7
- const token_1 = require("@croct/sdk/token");
8
- const sdk_1 = require("@croct/sdk");
9
- const constants_1 = require("./constants");
10
- const playground_1 = require("./playground");
11
- const preview_1 = require("./preview");
12
- const PLUGIN_NAMESPACE = 'Plugin';
1
+ import { SdkFacade } from "@croct/sdk/facade/sdkFacade";
2
+ import { formatCause } from "@croct/sdk/error";
3
+ import { describe } from "@croct/sdk/validation";
4
+ import { Token } from "@croct/sdk/token";
5
+ import { VERSION } from "@croct/sdk";
6
+ import { loadSlotContent } from "@croct/content";
7
+ import { CDN_URL } from "./constants.js";
8
+ import { factory as playgroundPluginFactory } from "./playground.js";
9
+ import { factory as previewPluginFactory } from "./preview.js";
10
+ const PLUGIN_NAMESPACE = "Plugin";
13
11
  function detectAppId() {
14
- const script = window.document.querySelector(`script[src^='${constants_1.CDN_URL}']`);
15
- if (!(script instanceof HTMLScriptElement)) {
16
- return null;
17
- }
18
- return (new URL(script.src)).searchParams.get('appId');
12
+ const script = window.document.querySelector(`script[src^='${CDN_URL}']`);
13
+ if (!(script instanceof HTMLScriptElement)) {
14
+ return null;
15
+ }
16
+ return new URL(script.src).searchParams.get("appId");
19
17
  }
20
18
  class GlobalPlug {
21
- constructor() {
22
- this.pluginFactories = {
23
- playground: playground_1.factory,
24
- preview: preview_1.factory,
25
- };
26
- this.plugins = {};
27
- this.ready = new Promise(resolve => {
28
- this.initialize = resolve;
29
- });
30
- }
31
- extend(name, plugin) {
32
- if (this.pluginFactories[name] !== undefined) {
33
- throw new Error(`Another plugin is already registered with name "${name}".`);
34
- }
35
- this.pluginFactories[name] = plugin;
36
- }
37
- plug(configuration = {}) {
38
- var _a, _b, _c;
39
- if (this.instance !== undefined) {
40
- const logger = this.instance.getLogger();
41
- logger.info('Croct is already plugged in.');
42
- return;
43
- }
44
- const detectedAppId = detectAppId();
45
- const configuredAppId = (_a = configuration.appId) !== null && _a !== void 0 ? _a : null;
46
- if (detectedAppId !== null && configuredAppId !== null && detectedAppId !== configuredAppId) {
47
- throw new Error('The specified app ID and the auto-detected app ID are conflicting. '
48
- + 'There is no need to specify an app ID when using an application-specific tag. '
49
- + 'Please try again omitting the "appId" option. '
50
- + 'For help, see https://croct.help/sdk/javascript/conflicting-app-id');
51
- }
52
- const appId = detectedAppId !== null && detectedAppId !== void 0 ? detectedAppId : configuredAppId;
53
- if (appId === null) {
54
- throw new Error('The app ID must be specified when it cannot be auto-detected. '
55
- + 'Please try again specifying the "appId" option.'
56
- + 'For help, see https://croct.help/sdk/javascript/missing-app-id');
57
- }
58
- const { plugins, test, ...sdkConfiguration } = configuration;
59
- const sdk = sdkFacade_1.SdkFacade.init({
60
- ...sdkConfiguration,
61
- appId: appId,
62
- test: test !== null && test !== void 0 ? test : (typeof process === 'object' && (((_b = process.env) === null || _b === void 0 ? void 0 : _b.CROCT_TEST_MODE) !== undefined
63
- ? process.env.CROCT_TEST_MODE === 'true'
64
- : ((_c = process.env) === null || _c === void 0 ? void 0 : _c.NODE_ENV) === 'test')),
65
- });
66
- this.instance = sdk;
67
- const logger = this.instance.getLogger();
68
- if (detectedAppId === configuredAppId) {
69
- logger.warn('It is strongly recommended omitting the "appId" option when using '
70
- + 'the application-specific tag as it is detected automatically.');
71
- }
72
- const pending = [];
73
- const defaultEnabledPlugins = Object.fromEntries(Object.keys(this.pluginFactories)
74
- .map(name => [name, true]));
75
- for (const [name, options] of Object.entries({ ...defaultEnabledPlugins, ...plugins })) {
76
- logger.debug(`Initializing plugin "${name}"...`);
77
- const factory = this.pluginFactories[name];
78
- if (factory === undefined) {
79
- logger.error(`Plugin "${name}" is not registered.`);
80
- continue;
81
- }
82
- if (typeof options !== 'boolean' && (options === null || typeof options !== 'object')) {
83
- logger.error(`Invalid options for plugin "${name}", `
84
- + `expected either boolean or object but got ${(0, validation_1.describe)(options)}`);
85
- continue;
86
- }
87
- if (options === false) {
88
- logger.warn(`Plugin "${name}" is declared but not enabled`);
89
- continue;
90
- }
91
- const args = {
92
- options: options === true ? {} : options,
93
- sdk: {
94
- version: sdk_1.VERSION,
95
- appId: appId,
96
- tracker: sdk.tracker,
97
- evaluator: sdk.evaluator,
98
- user: sdk.user,
99
- session: sdk.session,
100
- tab: sdk.context.getTab(),
101
- userTokenStore: {
102
- getToken: sdk.getToken.bind(sdk),
103
- setToken: sdk.setToken.bind(sdk),
104
- },
105
- previewTokenStore: sdk.previewTokenStore,
106
- cidAssigner: sdk.cidAssigner,
107
- eventManager: sdk.eventManager,
108
- getLogger: (...namespace) => sdk.getLogger(PLUGIN_NAMESPACE, name, ...namespace),
109
- getTabStorage: (...namespace) => (sdk.getTabStorage(PLUGIN_NAMESPACE, name, ...namespace)),
110
- getBrowserStorage: (...namespace) => (sdk.getBrowserStorage(PLUGIN_NAMESPACE, name, ...namespace)),
111
- },
112
- };
113
- let plugin;
114
- try {
115
- plugin = factory(args);
116
- }
117
- catch (error) {
118
- logger.error(`Failed to initialize plugin "${name}": ${(0, error_1.formatCause)(error)}`);
119
- continue;
120
- }
121
- logger.debug(`Plugin "${name}" initialized`);
122
- if (typeof plugin !== 'object') {
123
- continue;
124
- }
125
- this.plugins[name] = plugin;
126
- const promise = plugin.enable();
127
- if (!(promise instanceof Promise)) {
128
- logger.debug(`Plugin "${name}" enabled`);
129
- continue;
130
- }
131
- pending.push(promise.then(() => logger.debug(`Plugin "${name}" enabled`))
132
- .catch(error => logger.error(`Failed to enable plugin "${name}": ${(0, error_1.formatCause)(error)}`)));
133
- }
134
- Promise.all(pending)
135
- .then(() => {
136
- this.initialize();
137
- logger.debug('Initialization complete');
138
- });
139
- }
140
- get initialized() {
141
- return this.instance !== undefined;
142
- }
143
- get plugged() {
144
- return this.ready.then(() => this);
19
+ constructor() {
20
+ this.pluginFactories = {
21
+ playground: playgroundPluginFactory,
22
+ preview: previewPluginFactory
23
+ };
24
+ this.plugins = {};
25
+ this.ready = new Promise((resolve) => {
26
+ this.initialize = resolve;
27
+ });
28
+ }
29
+ extend(name, plugin) {
30
+ if (this.pluginFactories[name] !== void 0) {
31
+ throw new Error(`Another plugin is already registered with name "${name}".`);
145
32
  }
146
- get flushed() {
147
- return this.tracker
148
- .flushed
149
- .then(() => this);
33
+ this.pluginFactories[name] = plugin;
34
+ }
35
+ plug(configuration = {}) {
36
+ if (this.instance !== void 0) {
37
+ const logger2 = this.instance.getLogger();
38
+ logger2.info("Croct is already plugged in.");
39
+ return;
150
40
  }
151
- get sdk() {
152
- if (this.instance === undefined) {
153
- throw new Error('Croct is not plugged in. For help, see https://croct.help/sdk/javascript/not-plugged-in');
154
- }
155
- return this.instance;
156
- }
157
- get tracker() {
158
- return this.sdk.tracker;
159
- }
160
- get evaluator() {
161
- return this.sdk.evaluator;
41
+ const detectedAppId = detectAppId();
42
+ const configuredAppId = configuration.appId ?? null;
43
+ if (detectedAppId !== null && configuredAppId !== null && detectedAppId !== configuredAppId) {
44
+ throw new Error(
45
+ 'The specified app ID and the auto-detected app ID are conflicting. There is no need to specify an app ID when using an application-specific tag. Please try again omitting the "appId" option. For help, see https://croct.help/sdk/javascript/conflicting-app-id'
46
+ );
162
47
  }
163
- get user() {
164
- return this.sdk.user;
48
+ const appId = detectedAppId ?? configuredAppId;
49
+ if (appId === null) {
50
+ throw new Error(
51
+ 'The app ID must be specified when it cannot be auto-detected. Please try again specifying the "appId" option.For help, see https://croct.help/sdk/javascript/missing-app-id'
52
+ );
165
53
  }
166
- get session() {
167
- return this.sdk.session;
54
+ const { plugins, test, ...sdkConfiguration } = configuration;
55
+ if (sdkConfiguration.defaultPreferredLocale === "") {
56
+ delete sdkConfiguration.defaultPreferredLocale;
168
57
  }
169
- isAnonymous() {
170
- return this.sdk
171
- .context
172
- .isAnonymous();
58
+ const sdk = SdkFacade.init({
59
+ ...sdkConfiguration,
60
+ appId,
61
+ test: test ?? (typeof process === "object" && (process.env?.CROCT_TEST_MODE !== void 0 ? process.env.CROCT_TEST_MODE === "true" : process.env?.NODE_ENV === "test"))
62
+ });
63
+ this.instance = sdk;
64
+ const logger = this.instance.getLogger();
65
+ if (detectedAppId === configuredAppId) {
66
+ logger.warn(
67
+ 'It is strongly recommended omitting the "appId" option when using the application-specific tag as it is detected automatically.'
68
+ );
173
69
  }
174
- getUserId() {
175
- return this.sdk
176
- .context
177
- .getUser();
178
- }
179
- identify(userId) {
180
- if (typeof userId !== 'string') {
181
- throw new Error('The user ID must be a string. For help, see https://croct.help/sdk/javascript/invalid-user-id');
70
+ const pending = [];
71
+ const defaultEnabledPlugins = Object.fromEntries(
72
+ Object.keys(this.pluginFactories).map((name) => [name, true])
73
+ );
74
+ for (const [name, options] of Object.entries({ ...defaultEnabledPlugins, ...plugins })) {
75
+ logger.debug(`Initializing plugin "${name}"...`);
76
+ const factory = this.pluginFactories[name];
77
+ if (factory === void 0) {
78
+ logger.error(`Plugin "${name}" is not registered.`);
79
+ continue;
80
+ }
81
+ if (typeof options !== "boolean" && (options === null || typeof options !== "object")) {
82
+ logger.error(
83
+ `Invalid options for plugin "${name}", expected either boolean or object but got ${describe(options)}`
84
+ );
85
+ continue;
86
+ }
87
+ if (options === false) {
88
+ logger.warn(`Plugin "${name}" is declared but not enabled`);
89
+ continue;
90
+ }
91
+ const args = {
92
+ options: options === true ? {} : options,
93
+ sdk: {
94
+ version: VERSION,
95
+ appId,
96
+ tracker: sdk.tracker,
97
+ evaluator: sdk.evaluator,
98
+ user: sdk.user,
99
+ session: sdk.session,
100
+ tab: sdk.context.getTab(),
101
+ userTokenStore: {
102
+ getToken: sdk.getToken.bind(sdk),
103
+ setToken: sdk.setToken.bind(sdk)
104
+ },
105
+ previewTokenStore: sdk.previewTokenStore,
106
+ cidAssigner: sdk.cidAssigner,
107
+ eventManager: sdk.eventManager,
108
+ getLogger: (...namespace) => sdk.getLogger(PLUGIN_NAMESPACE, name, ...namespace),
109
+ getTabStorage: (...namespace) => sdk.getTabStorage(PLUGIN_NAMESPACE, name, ...namespace),
110
+ getBrowserStorage: (...namespace) => sdk.getBrowserStorage(PLUGIN_NAMESPACE, name, ...namespace)
182
111
  }
183
- this.sdk.identify(userId);
184
- }
185
- anonymize() {
186
- this.sdk.anonymize();
187
- }
188
- setToken(token) {
189
- this.sdk.setToken(token_1.Token.parse(token));
112
+ };
113
+ let plugin;
114
+ try {
115
+ plugin = factory(args);
116
+ } catch (error) {
117
+ logger.error(`Failed to initialize plugin "${name}": ${formatCause(error)}`);
118
+ continue;
119
+ }
120
+ logger.debug(`Plugin "${name}" initialized`);
121
+ if (typeof plugin !== "object") {
122
+ continue;
123
+ }
124
+ this.plugins[name] = plugin;
125
+ const promise = plugin.enable();
126
+ if (!(promise instanceof Promise)) {
127
+ logger.debug(`Plugin "${name}" enabled`);
128
+ continue;
129
+ }
130
+ pending.push(
131
+ promise.then(() => logger.debug(`Plugin "${name}" enabled`)).catch((error) => logger.error(`Failed to enable plugin "${name}": ${formatCause(error)}`))
132
+ );
190
133
  }
191
- unsetToken() {
192
- this.sdk.unsetToken();
134
+ Promise.all(pending).then(() => {
135
+ this.initialize();
136
+ logger.debug("Initialization complete");
137
+ });
138
+ }
139
+ get initialized() {
140
+ return this.instance !== void 0;
141
+ }
142
+ get plugged() {
143
+ return this.ready.then(() => this);
144
+ }
145
+ get flushed() {
146
+ return this.tracker.flushed.then(() => this);
147
+ }
148
+ get sdk() {
149
+ if (this.instance === void 0) {
150
+ throw new Error("Croct is not plugged in. For help, see https://croct.help/sdk/javascript/not-plugged-in");
193
151
  }
194
- track(type, payload) {
195
- return this.sdk
196
- .tracker
197
- .track(type, payload);
152
+ return this.instance;
153
+ }
154
+ get tracker() {
155
+ return this.sdk.tracker;
156
+ }
157
+ get evaluator() {
158
+ return this.sdk.evaluator;
159
+ }
160
+ get user() {
161
+ return this.sdk.user;
162
+ }
163
+ get session() {
164
+ return this.sdk.session;
165
+ }
166
+ isAnonymous() {
167
+ return this.sdk.context.isAnonymous();
168
+ }
169
+ getUserId() {
170
+ return this.sdk.context.getUser();
171
+ }
172
+ identify(userId) {
173
+ if (typeof userId !== "string") {
174
+ throw new Error(
175
+ "The user ID must be a string. For help, see https://croct.help/sdk/javascript/invalid-user-id"
176
+ );
198
177
  }
199
- evaluate(query, options = {}) {
200
- return this.sdk
201
- .evaluator
202
- .evaluate(query, options)
203
- .catch(error => {
204
- const logger = this.sdk.getLogger();
205
- const reference = query.length > 20 ? `${query.slice(0, 20)}...` : query;
206
- logger.error(`Failed to evaluate query "${reference}": ${(0, error_1.formatCause)(error)}`);
207
- throw error;
208
- });
178
+ this.sdk.identify(userId);
179
+ }
180
+ anonymize() {
181
+ this.sdk.anonymize();
182
+ }
183
+ setToken(token) {
184
+ this.sdk.setToken(Token.parse(token));
185
+ }
186
+ unsetToken() {
187
+ this.sdk.unsetToken();
188
+ }
189
+ track(type, payload) {
190
+ return this.sdk.tracker.track(type, payload);
191
+ }
192
+ evaluate(query, options = {}) {
193
+ return this.sdk.evaluator.evaluate(query, options).catch((error) => {
194
+ const logger = this.sdk.getLogger();
195
+ const reference = query.length > 20 ? `${query.slice(0, 20)}...` : query;
196
+ logger.error(`Failed to evaluate query "${reference}": ${formatCause(error)}`);
197
+ throw error;
198
+ });
199
+ }
200
+ test(expression, options = {}) {
201
+ return this.evaluate(expression, options).then((result) => result === true);
202
+ }
203
+ fetch(slotId, { fallback, ...options } = {}) {
204
+ const [id, version = "latest"] = slotId.split("@");
205
+ const logger = this.sdk.getLogger();
206
+ const preferredLocale = options.preferredLocale !== void 0 && options.preferredLocale !== "" ? options.preferredLocale : void 0;
207
+ return this.sdk.contentFetcher.fetch(id, {
208
+ ...options,
209
+ preferredLocale,
210
+ version: version === "latest" ? void 0 : version
211
+ }).catch(async (error) => {
212
+ logger.error(`Failed to fetch content for slot "${id}@${version}": ${formatCause(error)}`);
213
+ const resolvedFallback = fallback === void 0 ? await loadSlotContent(slotId, preferredLocale) ?? void 0 : fallback;
214
+ if (resolvedFallback === void 0) {
215
+ throw error;
216
+ }
217
+ return { content: resolvedFallback };
218
+ });
219
+ }
220
+ async unplug() {
221
+ if (this.instance === void 0) {
222
+ return;
209
223
  }
210
- test(expression, options = {}) {
211
- return this.evaluate(expression, options)
212
- .then(result => result === true);
224
+ const { instance, plugins } = this;
225
+ const logger = this.sdk.getLogger();
226
+ const pending = [];
227
+ for (const [pluginName, controller] of Object.entries(plugins)) {
228
+ if (typeof controller.disable !== "function") {
229
+ continue;
230
+ }
231
+ logger.debug(`Disabling plugin "${pluginName}"...`);
232
+ const promise = controller.disable();
233
+ if (!(promise instanceof Promise)) {
234
+ logger.debug(`Plugin "${pluginName}" disabled`);
235
+ continue;
236
+ }
237
+ pending.push(
238
+ promise.then(() => logger.debug(`Plugin "${pluginName}" disabled`)).catch((error) => logger.error(`Failed to disable "${pluginName}": ${formatCause(error)}`))
239
+ );
213
240
  }
214
- fetch(slotId, options = {}) {
215
- const [id, version = 'latest'] = slotId.split('@');
216
- const logger = this.sdk.getLogger();
217
- return this.sdk
218
- .contentFetcher
219
- .fetch(id, version === 'latest' ? options : { ...options, version: version })
220
- .catch(error => {
221
- logger.error(`Failed to fetch content for slot "${id}@${version}": ${(0, error_1.formatCause)(error)}`);
222
- throw error;
223
- });
224
- }
225
- async unplug() {
226
- if (this.instance === undefined) {
227
- return;
228
- }
229
- const { instance, plugins } = this;
230
- const logger = this.sdk.getLogger();
231
- const pending = [];
232
- for (const [pluginName, controller] of Object.entries(plugins)) {
233
- if (typeof controller.disable !== 'function') {
234
- continue;
235
- }
236
- logger.debug(`Disabling plugin "${pluginName}"...`);
237
- const promise = controller.disable();
238
- if (!(promise instanceof Promise)) {
239
- logger.debug(`Plugin "${pluginName}" disabled`);
240
- continue;
241
- }
242
- pending.push(promise.then(() => logger.debug(`Plugin "${pluginName}" disabled`))
243
- .catch(error => logger.error(`Failed to disable "${pluginName}": ${(0, error_1.formatCause)(error)}`)));
244
- }
245
- // Reset
246
- delete this.instance;
247
- this.plugins = {};
248
- this.ready = new Promise(resolve => {
249
- this.initialize = resolve;
250
- });
251
- await Promise.all(pending);
252
- try {
253
- await instance.close();
254
- }
255
- finally {
256
- logger.info('🔌 Croct has been unplugged.');
257
- }
241
+ delete this.instance;
242
+ this.plugins = {};
243
+ this.ready = new Promise((resolve) => {
244
+ this.initialize = resolve;
245
+ });
246
+ await Promise.all(pending);
247
+ try {
248
+ await instance.close();
249
+ } finally {
250
+ logger.info("\u{1F50C} Croct has been unplugged.");
258
251
  }
252
+ }
259
253
  }
260
- exports.GlobalPlug = GlobalPlug;
261
- //# sourceMappingURL=plug.js.map
254
+ export {
255
+ GlobalPlug
256
+ };
package/plugin.cjs ADDED
@@ -0,0 +1,15 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
+ var plugin_exports = {};
15
+ module.exports = __toCommonJS(plugin_exports);
package/plugin.d.cts ADDED
@@ -0,0 +1,41 @@
1
+ import { TokenStore } from '@croct/sdk/token';
2
+ import { EvaluatorFacade } from '@croct/sdk/facade/evaluatorFacade';
3
+ import { TrackerFacade } from '@croct/sdk/facade/trackerFacade';
4
+ import { SdkEventManager } from './sdk/index.cjs';
5
+ import { UserFacade } from '@croct/sdk/facade/userFacade';
6
+ import { SessionFacade } from '@croct/sdk/facade/sessionFacade';
7
+ import { Tab } from '@croct/sdk/tab';
8
+ import { CidAssigner } from '@croct/sdk/cid';
9
+ import { Logger } from '@croct/sdk/logging';
10
+ import '@croct/sdk/eventManager';
11
+ import '@croct/sdk/sdkEvents';
12
+
13
+ interface PluginSdk {
14
+ readonly version: string;
15
+ readonly appId: string;
16
+ readonly tracker: TrackerFacade;
17
+ readonly evaluator: EvaluatorFacade;
18
+ readonly user: UserFacade;
19
+ readonly session: SessionFacade;
20
+ readonly tab: Tab;
21
+ readonly userTokenStore: TokenStore;
22
+ readonly previewTokenStore: TokenStore;
23
+ readonly cidAssigner: CidAssigner;
24
+ readonly eventManager: SdkEventManager;
25
+ getLogger(...namespace: string[]): Logger;
26
+ getTabStorage(...namespace: string[]): Storage;
27
+ getBrowserStorage(...namespace: string[]): Storage;
28
+ }
29
+ interface PluginArguments<T = any> {
30
+ options: T;
31
+ sdk: PluginSdk;
32
+ }
33
+ interface PluginFactory<T = any> {
34
+ (args: PluginArguments<T>): Plugin;
35
+ }
36
+ interface Plugin {
37
+ enable(): Promise<void> | void;
38
+ disable?(): Promise<void> | void;
39
+ }
40
+
41
+ export type { Plugin, PluginArguments, PluginFactory, PluginSdk };