@jolibox/sdk 0.0.7 → 1.0.0-beta.0

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 (83) hide show
  1. package/.eslintrc.js +3 -0
  2. package/.rush/temp/package-deps_build.json +28 -0
  3. package/.rush/temp/shrinkwrap-deps.json +76 -0
  4. package/README.md +1 -91
  5. package/dist/api/__tests__/canIUse.test.d.ts +1 -0
  6. package/dist/api/can-i-use.d.ts +1 -0
  7. package/dist/api/get-system-info.d.ts +3 -0
  8. package/dist/api/index.d.ts +2 -0
  9. package/dist/errors.d.ts +2 -0
  10. package/dist/index.cjs.js +1 -0
  11. package/dist/index.d.ts +19 -309
  12. package/dist/index.es.js +1 -0
  13. package/dist/loader/h5.d.ts +6 -0
  14. package/dist/loader/index.d.ts +16 -0
  15. package/dist/loader/native.d.ts +6 -0
  16. package/dist/loader/version.d.ts +2 -0
  17. package/dist/sdks/ads.d.ts +11 -0
  18. package/dist/sdks/keyboard.d.ts +34 -0
  19. package/dist/sdks/lifecycle.d.ts +16 -0
  20. package/dist/sdks/runtime.d.ts +1 -0
  21. package/dist/sdks/sdk.d.ts +11 -0
  22. package/dist/sdks/storage.d.ts +8 -0
  23. package/dist/utils/can-i-use.d.ts +2 -0
  24. package/dist/utils/report.d.ts +3 -0
  25. package/package.json +24 -34
  26. package/sdk.build.log +13 -0
  27. package/src/api/__tests__/canIUse.test.ts +76 -0
  28. package/src/api/can-i-use.ts +38 -0
  29. package/src/api/get-system-info.ts +14 -0
  30. package/src/api/index.ts +2 -0
  31. package/src/errors.ts +42 -0
  32. package/src/index.ts +29 -0
  33. package/src/loader/h5.ts +175 -0
  34. package/src/loader/index.ts +65 -0
  35. package/src/loader/native.ts +62 -0
  36. package/src/loader/version.ts +44 -0
  37. package/src/sdks/ads.ts +32 -0
  38. package/src/sdks/keyboard.ts +50 -0
  39. package/src/sdks/lifecycle.ts +32 -0
  40. package/src/sdks/runtime.ts +3 -0
  41. package/src/sdks/sdk.ts +22 -0
  42. package/src/sdks/storage.ts +35 -0
  43. package/src/utils/can-i-use.ts +24 -0
  44. package/src/utils/report.ts +23 -0
  45. package/tsconfig.json +12 -107
  46. package/README-zh_cn.md +0 -91
  47. package/dist/index.cjs +0 -2
  48. package/dist/index.cjs.map +0 -1
  49. package/dist/index.d.cts +0 -314
  50. package/dist/index.iife.js +0 -2
  51. package/dist/index.iife.js.map +0 -1
  52. package/dist/index.js +0 -2
  53. package/dist/index.js.map +0 -1
  54. package/docs/.nojekyll +0 -1
  55. package/docs/assets/highlight.css +0 -106
  56. package/docs/assets/icons.js +0 -18
  57. package/docs/assets/icons.svg +0 -1
  58. package/docs/assets/main.js +0 -60
  59. package/docs/assets/navigation.js +0 -1
  60. package/docs/assets/search.js +0 -1
  61. package/docs/assets/style.css +0 -1493
  62. package/docs/classes/index.JoliboxAds.html +0 -41
  63. package/docs/classes/index.JoliboxRuntime.html +0 -8
  64. package/docs/classes/index.JoliboxSDK.html +0 -4
  65. package/docs/documents/README.html +0 -39
  66. package/docs/enums/index.JoliboxRuntimeEvents.html +0 -7
  67. package/docs/index.html +0 -39
  68. package/docs/interfaces/index.IAdConfigParams.html +0 -12
  69. package/docs/interfaces/index.IAdUnitParams.html +0 -11
  70. package/docs/interfaces/index.IAdsInitParams.html +0 -5
  71. package/docs/interfaces/index.IInterstitialsParams.html +0 -15
  72. package/docs/interfaces/index.IJoliboxConfig.html +0 -3
  73. package/docs/interfaces/index.IJoliboxSDKLoaderConfig.html +0 -3
  74. package/docs/interfaces/index.IPlacementInfo.html +0 -59
  75. package/docs/interfaces/index.IPrerollParams.html +0 -6
  76. package/docs/interfaces/index.IRewardParams.html +0 -18
  77. package/docs/interfaces/index.IVersionMetadata.html +0 -4
  78. package/docs/modules/index.html +0 -18
  79. package/docs/modules.html +0 -3
  80. package/docs/types/index.AdUnitFormat.html +0 -2
  81. package/docs/types/index.IAdBreakParams.html +0 -2
  82. package/tsup.config.ts +0 -27
  83. package/typedoc.config.mjs +0 -17
@@ -0,0 +1,65 @@
1
+ import { major } from './version';
2
+
3
+ import { createLoadImplement as createH5LoadImplement } from './h5';
4
+ import { createLoadImplement as createNativeLoadImplement } from './native';
5
+ //TODO: temp
6
+ const BUILD_VERSION = '1.0.0';
7
+ const currentVersion = BUILD_VERSION;
8
+ const currentMajorVersion = major(currentVersion);
9
+
10
+ /**
11
+ * Due to security restrictions on iOS, dynamically loading script tags is not supported.
12
+ * Therefore, a loadScript method needs to be injected on the client side to implement evalJavascriptFun.
13
+ * Link:https://mabin004.github.io/2018/06/25/iOS%E5%BA%94%E7%94%A8%E6%B2%99%E7%AE%B1/
14
+ */
15
+
16
+ declare global {
17
+ interface Window {
18
+ // WebBridge: AndroidBridge | null;
19
+ webkit?: unknown;
20
+ }
21
+ }
22
+ const loadScript = window.webkit
23
+ ? (params: { path: string }) => {
24
+ return window.prompt('loadScript', JSON.stringify(params));
25
+ }
26
+ : undefined;
27
+
28
+ const isNative = typeof loadScript !== 'undefined';
29
+
30
+ /**
31
+ * Do not expose the logic of dynamically retrieving URL information in the config,
32
+ * as this logic needs to remain self-contained within the SDK.
33
+ */
34
+ export const getBoostrapModuleUrl = (version: string | number) =>
35
+ `http://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${version}/dist/index.js`;
36
+ export const getImplementModuleUrl = (version: string | number) =>
37
+ `http://cdn.jsdelivr.net/npm/@jolibox/implement@${version}/dist/index.js`;
38
+ /**
39
+ * localTest
40
+ */
41
+ // export const getBoostrapModuleUrl = (version: string | number) => `http://localhost:3000/get-bootstrap`;
42
+ // export const getImplementModuleUrl = (version: string | number) => `http://localhost:3000/get-implement`;
43
+ const IMMEDIATE_SCRIPT_URL = getBoostrapModuleUrl(currentMajorVersion);
44
+ const REMOTE_IMPLEMENT_URL = getImplementModuleUrl(currentMajorVersion);
45
+
46
+ /**
47
+ * load entry
48
+ */
49
+ function loadImplement(): void {
50
+ if (isNative) {
51
+ createNativeLoadImplement(loadScript!, {
52
+ bootstrapUrl: IMMEDIATE_SCRIPT_URL,
53
+ implementUrl: REMOTE_IMPLEMENT_URL
54
+ })();
55
+ } else {
56
+ createH5LoadImplement({
57
+ bootstrapUrl: IMMEDIATE_SCRIPT_URL,
58
+ implementUrl: REMOTE_IMPLEMENT_URL,
59
+ currentMajorVersion,
60
+ currentVersion
61
+ })();
62
+ }
63
+ }
64
+
65
+ loadImplement();
@@ -0,0 +1,62 @@
1
+ import { track, trackPerformance } from '@/utils/report';
2
+ import { InternalJSModuleEvalError } from '@jolibox/common';
3
+ import { reportError } from '../errors';
4
+
5
+ export const createLoadImplement = (
6
+ loadScript: (params: { path: string }) => string | null,
7
+ params: {
8
+ bootstrapUrl: string;
9
+ implementUrl: string;
10
+ }
11
+ ) => {
12
+ const tryLoadScript = (url: string): string => {
13
+ const funStr = loadScript!({ path: url });
14
+ if (!funStr) {
15
+ throw `module ${url} load failed ${funStr}`;
16
+ }
17
+ return funStr;
18
+ };
19
+
20
+ function evalLocalJSModule(code: string) {
21
+ const evalJS = async (code: string) => {
22
+ try {
23
+ const blob = new Blob([code], { type: 'application/javascript' });
24
+ const blobUrl = URL.createObjectURL(blob);
25
+ const module = await import(blobUrl);
26
+ URL.revokeObjectURL(blobUrl);
27
+ return module;
28
+ } catch (error) {
29
+ reportError(new InternalJSModuleEvalError(`implement module evaluate error in native:${error} `));
30
+ }
31
+ };
32
+ evalJS(code);
33
+ }
34
+ return () => {
35
+ try {
36
+ const startToLoad = Date.now();
37
+ track('js_sdk_begin', {
38
+ t: startToLoad
39
+ });
40
+ /**
41
+ * bootstrap module
42
+ */
43
+ const bootstrapModuleStr = tryLoadScript(params.bootstrapUrl);
44
+ const script = document.createElement('script');
45
+ script.type = 'text/javascript';
46
+ script.innerHTML = bootstrapModuleStr;
47
+ document.head.appendChild(script);
48
+ trackPerformance('implementModuleLoaded', Date.now() - startToLoad, { type: 'native' });
49
+
50
+ /**
51
+ * implement module
52
+ */
53
+ const implModuleStr = tryLoadScript(params.implementUrl);
54
+ evalLocalJSModule(implModuleStr);
55
+ trackPerformance('bootstrapModuleLoaded', Date.now() - startToLoad, { type: 'native' });
56
+ } catch (e) {
57
+ console.error(`native load script error: ${e}`);
58
+ // TODO
59
+ reportError(new InternalJSModuleEvalError(`module load failed ${e}`));
60
+ }
61
+ };
62
+ };
@@ -0,0 +1,44 @@
1
+ const splitSemver = (
2
+ version: string
3
+ ): {
4
+ major: string;
5
+ minor: string;
6
+ patch: string;
7
+ prerelease?: string;
8
+ build?: string;
9
+ } => {
10
+ const prerelease = version.split('-')[1] as string | undefined;
11
+ if (prerelease) {
12
+ version = version.replace(`-${prerelease}`, '');
13
+ }
14
+
15
+ const build = version.split('+')[1] as string | undefined;
16
+ if (build) {
17
+ version = version.replace(`+${build}`, '');
18
+ }
19
+
20
+ const splitted = version.split('.').slice(0, 3);
21
+ const [major, minor, patch] = [splitted[0] ?? '0', splitted[1] ?? '0', splitted[2] ?? '0'];
22
+ return { major, minor, patch, prerelease, build };
23
+ };
24
+
25
+ export const major = (version: string): number => parseInt(splitSemver(version).major, 10);
26
+
27
+ export const compare = (v1: string, v2: string): -1 | 0 | 1 => {
28
+ const { major: major1, minor: minor1, patch: patch1 } = splitSemver(v1);
29
+ const { major: major2, minor: minor2, patch: patch2 } = splitSemver(v2);
30
+
31
+ if (major1 !== major2) {
32
+ return major1 > major2 ? 1 : -1;
33
+ }
34
+
35
+ if (minor1 !== minor2) {
36
+ return minor1 > minor2 ? 1 : -1;
37
+ }
38
+
39
+ if (patch1 !== patch2) {
40
+ return patch1 > patch2 ? 1 : -1;
41
+ }
42
+
43
+ return 0;
44
+ };
@@ -0,0 +1,32 @@
1
+ import type {
2
+ IAdBreakParams,
3
+ IAdConfigParams,
4
+ IAdsInitParams,
5
+ IAdUnitParams,
6
+ JoliboxAds as IJoliboxAds
7
+ } from '@jolibox/types/dist/sdks/ads';
8
+ import { BaseSDK, BaseSDKEventMap } from './sdk';
9
+
10
+ type JoliboxAdsEventMap = BaseSDKEventMap
11
+
12
+ export class JoliboxAds extends BaseSDK<JoliboxAdsEventMap> implements IJoliboxAds {
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ init = (config?: IAdsInitParams) => {
18
+ this.commands.executeCommand('AdsSDK.init', config);
19
+ };
20
+
21
+ adConfig = (params: IAdConfigParams) => {
22
+ this.commands.executeCommand('AdsSDK.adConfig', params);
23
+ };
24
+
25
+ adBreak = (params: IAdBreakParams) => {
26
+ this.commands.executeCommand('AdsSDK.adBreak', params);
27
+ };
28
+
29
+ adUnit = (params: IAdUnitParams) => {
30
+ this.commands.executeCommand('AdsSDK.adUnit', params);
31
+ };
32
+ }
@@ -0,0 +1,50 @@
1
+ import { BaseSDK } from './sdk';
2
+ import { Keyboard, ResponseType } from '@jolibox/types';
3
+
4
+ export class KeyboardSDK extends BaseSDK implements Keyboard {
5
+ /**
6
+ * 显示键盘
7
+ * @param params
8
+ * @returns
9
+ */
10
+ showKeyboard(params: { defaultValue?: string; maxLength?: number; multiple?: boolean }) {
11
+ const canUse = this.canUse('keyboard.showKeyboard');
12
+ if (!canUse) {
13
+ return {
14
+ code: 'FAILURE' as ResponseType,
15
+ message: `[Jolibox SDK] keyboard.showKeyboard is not supported in this platform`
16
+ };
17
+ }
18
+
19
+ this.commands.executeCommand('KeyboardSDK.showKeyboard', params);
20
+ }
21
+ /**
22
+ * 更新键盘
23
+ * @param value
24
+ * @returns
25
+ */
26
+ updateKeyboard(value: string) {
27
+ const canUse = this.canUse('keyboard.updateKeyboard');
28
+ if (!canUse) {
29
+ return {
30
+ code: 'FAILURE' as ResponseType,
31
+ message: `[Jolibox SDK] keyboard.updateKeyboard is not supported in this platform`
32
+ };
33
+ }
34
+ this.commands.executeCommand('KeyboardSDK.updateKeyboard', value);
35
+ }
36
+ /**
37
+ * 隐藏键盘
38
+ * @returns
39
+ */
40
+ hideKeyboard() {
41
+ const canUse = this.canUse('keyboard.hideKeyboard');
42
+ if (!canUse) {
43
+ return {
44
+ code: 'FAILURE' as ResponseType,
45
+ message: `[Jolibox SDK] keyboard.hideKeyboard is not supported in this platform`
46
+ };
47
+ }
48
+ this.commands.executeCommand('KeyboardSDK.hideKeyboard');
49
+ }
50
+ }
@@ -0,0 +1,32 @@
1
+ import { Env, Lifecycle } from '@jolibox/types';
2
+ import { BaseSDK, BaseSDKEventMap } from './sdk';
3
+
4
+ const LIFECYCLE_ON_READY = 'LifecycleSDK.onReady';
5
+ interface LifecycleSDKEventMap extends BaseSDKEventMap {
6
+ [LIFECYCLE_ON_READY]: Env['hostUserInfo'] | undefined;
7
+ }
8
+
9
+ export class LifecycleSDK extends BaseSDK<LifecycleSDKEventMap> implements Lifecycle {
10
+ constructor() {
11
+ super();
12
+ }
13
+
14
+ onReady(callback: (info?: Env['hostUserInfo']) => void) {
15
+ const wrappedOnReady = (info?: Env['hostUserInfo']) => {
16
+ callback.call(this, info);
17
+ this.triggerEvent(LIFECYCLE_ON_READY, info);
18
+ };
19
+ this.commands.executeCommand('LifecycleSDK.onReady', wrappedOnReady.bind(this));
20
+ }
21
+
22
+ exitGame(params: { onBeforeExit: () => void }) {
23
+ this.commands.executeCommand('LifecycleSDK.exitGame', params.onBeforeExit);
24
+ }
25
+
26
+ onGameHide(params: () => void) {
27
+ this.commands.executeCommand('LifecycleSDK.onGameHide', params.bind(this));
28
+ }
29
+ onGameShow(params: () => void) {
30
+ this.commands.executeCommand('LifecycleSDK.onGameShow', params.bind(this));
31
+ }
32
+ }
@@ -0,0 +1,3 @@
1
+ //eslint-disable-next-line @typescript-eslint/ban-ts-comment
2
+ //@ts-ignore
3
+ export const RuntimeSDK = window.JoliboxRuntime;
@@ -0,0 +1,22 @@
1
+ import { canIUse } from '@/api';
2
+ import { createCommands, EventEmitter } from '@jolibox/common';
3
+ export interface BaseSDKEventMap {
4
+ _baseSDKMarker?: never;
5
+ }
6
+
7
+ export abstract class BaseSDK<T = BaseSDKEventMap> {
8
+ readonly commands = createCommands();
9
+ readonly _emitter = new EventEmitter();
10
+
11
+ addEventListener<K extends keyof T & string>(event: K, callback: (data: T[K]) => void) {
12
+ this._emitter.on(event, (...args) => callback(args[0] as T[K]));
13
+ }
14
+
15
+ triggerEvent<K extends keyof T & string>(event: K, params: T[K]) {
16
+ this._emitter.emit(event, params);
17
+ }
18
+
19
+ canUse(command: string) {
20
+ return canIUse(command);
21
+ }
22
+ }
@@ -0,0 +1,35 @@
1
+ import { BaseSDK } from './sdk';
2
+ import { StandardResponse, Storage } from '@jolibox/types';
3
+
4
+ export class StorageSDK extends BaseSDK implements Storage {
5
+ async getItem(key: string) {
6
+ const result = await this.commands.executeCommand('StorageSDK.getItem', key);
7
+ return result;
8
+ }
9
+
10
+ async setItem(key: string, value: number | string | boolean): Promise<StandardResponse<void>> {
11
+ if (key.length > 128) {
12
+ return {
13
+ code: 'PARAMETER_ERROR',
14
+ message: '[SDK] cloud storage setItem error: length of key should be less than 128'
15
+ };
16
+ }
17
+
18
+ const valueToStore = typeof value == 'string' ? value : String(value);
19
+ if (key.length + valueToStore.length > 1024) {
20
+ return {
21
+ code: 'PARAMETER_ERROR',
22
+ message: '[SDK] cloud storage setItem error: length of key and value should be less than 1024'
23
+ };
24
+ }
25
+ return await this.commands.executeCommand('StorageSDK.setItem', key, value);
26
+ }
27
+
28
+ async removeItem(key: string) {
29
+ return this.commands.executeCommand('StorageSDK.removeItem', key);
30
+ }
31
+
32
+ async clear() {
33
+ return this.commands.executeCommand('StorageSDK.clear');
34
+ }
35
+ }
@@ -0,0 +1,24 @@
1
+ import { canIUseConfig } from '@jolibox/common';
2
+
3
+ export function getCanIUseConfig(platform: 'h5' | 'native', key: string) {
4
+ return canIUseConfig.config[platform]?.[key];
5
+ }
6
+
7
+ export function get<T extends Record<string, any>, P extends string | string[], Default = undefined>(
8
+ obj: T,
9
+ path: P,
10
+ defaultValue?: Default
11
+ ): unknown {
12
+ const pathArray = Array.isArray(path) ? path : (path as string).replace(/\[(\d+)\]/g, '.$1').split('.');
13
+
14
+ let result: any = obj;
15
+ for (const key of pathArray) {
16
+ if (result && (typeof result === 'object' || Array.isArray(result))) {
17
+ result = result[key];
18
+ } else {
19
+ return defaultValue as any;
20
+ }
21
+ }
22
+
23
+ return result === undefined ? defaultValue : result;
24
+ }
@@ -0,0 +1,23 @@
1
+ import { createCommands } from '@jolibox/common';
2
+ import { TrackEvent, PerformanceType } from '@jolibox/types';
3
+
4
+ const commands = createCommands();
5
+
6
+ export const track = (event: TrackEvent, info: Record<string, unknown>) => {
7
+ commands.executeCommand('ReportSDK.traceSystem', {
8
+ event,
9
+ info
10
+ });
11
+ };
12
+
13
+ export const trackPerformance = (
14
+ event: PerformanceType,
15
+ duration: number,
16
+ extra?: Record<string, unknown>
17
+ ) => {
18
+ commands.executeCommand('ReportSDK.traceSystemTimeline', {
19
+ event,
20
+ duration,
21
+ extra
22
+ });
23
+ };
package/tsconfig.json CHANGED
@@ -1,111 +1,16 @@
1
1
  {
2
+ "extends": "../../tsconfig.json",
2
3
  "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
-
27
- /* Modules */
28
- "module": "ESNext", /* Specify what module code is generated. */
29
- // "rootDir": "./", /* Specify the root folder within your source files. */
30
- "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
- // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
43
- "resolveJsonModule": true, /* Enable importing .json files. */
44
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
45
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
46
-
47
- /* JavaScript Support */
48
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
49
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
50
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
51
-
52
- /* Emit */
53
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
54
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
55
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
56
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
57
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
58
- // "noEmit": true, /* Disable emitting files from a compilation. */
59
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
60
- // "outDir": "./", /* Specify an output folder for all emitted files. */
61
- // "removeComments": true, /* Disable emitting comments. */
62
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
63
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
- // "newLine": "crlf", /* Set the newline character for emitting files. */
69
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
-
75
- /* Interop Constraints */
76
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
77
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
78
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
79
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83
-
84
- /* Type Checking */
85
- "strict": true, /* Enable all strict type-checking options. */
86
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
- // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
92
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
93
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
94
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
95
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
96
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
97
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
98
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
99
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
100
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
101
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
102
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
103
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
104
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
105
-
106
- /* Completeness */
107
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
108
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
4
+ "rootDir": "./src",
5
+ "outDir": "./dist",
6
+ "declaration": true,
7
+ "emitDeclarationOnly": true,
8
+ "noEmit": false,
9
+ "baseUrl": ".",
10
+ "paths": {
11
+ "@/*": ["src/*"]
12
+ }
109
13
  },
110
- "exclude": ["dist"]
14
+ "include": ["src/**/*"],
15
+ "exclude": ["dist/", "node_modules"]
111
16
  }
package/README-zh_cn.md DELETED
@@ -1,91 +0,0 @@
1
- # Jolibox Ads SDK
2
-
3
- Jolibox SDK 是一个 JavaScript 库,提供了一种简单的方法来集成 Jolibox 广告、运行时和其他服务。
4
-
5
- **当前版本仍处于预发布阶段,因此 API 可能会在未来发生变化。**
6
-
7
- ## 安装
8
-
9
- ### 通过 CDN 引入
10
-
11
- 如果你想通过 CDN 使用该库,可以在你的 HTML 文件中添加以下脚本标签。
12
-
13
- 在这种情况下,你不应该在你的 JavaScript 文件中编写 import 语句。
14
-
15
- ```html
16
- <script src="https://cdn.jsdelivr.net/npm/@jolibox/sdk@0.0.7/dist/index.iife.js"></script>
17
- ```
18
-
19
- ### 通过 NPM 安装
20
-
21
- 如果你想通过 NPM 使用该库,可以通过以下命令安装它:
22
-
23
- 在这种情况下,你不应该在你的 HTML 文件中包含脚本标签,而是在你的 JavaScript 文件中编写 import 语句。
24
-
25
- - npm
26
-
27
- ```bash
28
- npm install @jolibox/sdk
29
- ```
30
-
31
- - pnpm
32
-
33
- ```bash
34
- pnpm add @jolibox/sdk
35
- ```
36
-
37
- - yarn
38
-
39
- ```bash
40
- yarn add @jolibox/sdk
41
- ```
42
-
43
- ## 基本用法
44
-
45
- - 初始化
46
-
47
- ```typescript
48
- // 如果你通过 NPM 导入库,你可以使用以下 import 语句
49
- // import { JoliboxSDK } from "@jolibox/sdk";
50
-
51
- const jolibox = new JoliboxSDK({
52
- loaderConfig: {
53
- testMode: true,
54
- },
55
- });
56
-
57
- // 例如,如果你想使用广告服务
58
- const { ads } = jolibox;
59
- ads.init({ testMode: true });
60
-
61
- // 在需要预加载广告的地方(例如在游戏加载屏幕中)
62
- ads.adConfig({
63
- preloadAdBreaks: "on",
64
- sound: "on",
65
- onReady: () => {
66
- console.log("onReady");
67
- },
68
- });
69
-
70
- // 在需要弹出奖励广告的地方
71
- ads.adBreak({
72
- type: "reward",
73
- beforeReward(showAdFn) {
74
- showAdFn();
75
- },
76
- adDismissed: () => {
77
- console.log("adDismissed");
78
- },
79
- adViewed: () => {
80
- console.log("adViewed");
81
- },
82
- adBreakDone: () => {
83
- console.log("adBreakDone");
84
- },
85
- });
86
-
87
- // 如果需要显示横幅广告,应在应用启动时调用以下函数
88
- ads.adUnit({
89
- el: "#banner", // 或者 document.getElementById("banner")
90
- });
91
- ```
package/dist/index.cjs DELETED
@@ -1,2 +0,0 @@
1
- "use strict";var m=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var y=(t,e)=>{for(var o in e)m(t,o,{get:e[o],enumerable:!0})},J=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of g(e))!S.call(t,a)&&a!==o&&m(t,a,{get:()=>e[a],enumerable:!(r=h(e,a))||r.enumerable});return t};var j=t=>J(m({},"__esModule",{value:!0}),t);var p=(t,e,o)=>new Promise((r,a)=>{var n=i=>{try{s(o.next(i))}catch(d){a(d)}},l=i=>{try{s(o.throw(i))}catch(d){a(d)}},s=i=>i.done?r(i.value):Promise.resolve(i.value).then(n,l);s((o=o.apply(t,e)).next())});var _={};y(_,{JoliboxSDK:()=>c,default:()=>L});module.exports=j(_);var f=t=>{var s,i,d;let e=t.split("-")[1];e&&(t=t.replace(`-${e}`,""));let o=t.split("+")[1];o&&(t=t.replace(`+${o}`,""));let r=t.split(".").slice(0,3),[a,n,l]=[(s=r[0])!=null?s:"0",(i=r[1])!=null?i:"0",(d=r[2])!=null?d:"0"];return{major:a,minor:n,patch:l,prerelease:e,build:o}},w=t=>parseInt(f(t).major,10),I=(t,e)=>{let{major:o,minor:r,patch:a}=f(t),{major:n,minor:l,patch:s}=f(e);return o!==n?o>n?1:-1:r!==l?r>l?1:-1:a!==s?a>s?1:-1:0};var u="jolibox-sdk-loader-metadata",x=class{constructor({testMode:e,loaderMetadata:o}={}){this.testMode=!1;this.computeLoaderMetaData=()=>{var a,n;let e=this.currentVersion,o=null;try{if(o=JSON.parse((a=localStorage.getItem(u))!=null?a:"null"),!o||!o.version)throw new Error("Invalid loader metadata")}catch(l){o=this.defaultMetadata}let r=(n=o==null?void 0:o.version)!=null?n:e;return w(r)!==w(e)?o=this.defaultMetadata:I(r,e)<0&&(o=this.defaultMetadata),o};this.loadScript=()=>{if(this.loaderMetadata.syncScriptUrl){let e=new XMLHttpRequest;e.open("GET",this.loaderMetadata.syncScriptUrl,!1),e.send();let o=document.createElement("script");o.type="text/javascript",o.innerHTML=e.responseText,document.head.appendChild(o)}if(this.loaderMetadata.asyncScriptUrl){let e=document.createElement("script");e.type="text/javascript",e.src=this.loaderMetadata.asyncScriptUrl,e.async=!0,document.head.appendChild(e)}};this.fetchUpdateLoaderMetadata=(...n)=>p(this,[...n],function*(e=this.currentVersion,o=this.loaderMetadata.version,r=(a=>(a=window.JOLIBOX_ENV)!=null?a:"WEB")()){var s;let l=`${this.apiBaseURL}/frontend/js-sdk/loader-metadata`;try{let d=yield(yield fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({installedSDKVersion:e,localSDKVersion:o,env:r})})).json();if(d.code!=="SUCCESS")throw new Error(d.message);this.loaderMetadata=(s=d.data)!=null?s:this.defaultMetadata,localStorage.setItem(u,JSON.stringify(this.loaderMetadata))}catch(i){console.warn("Failed to fetch loader metadata: ",i)}});console.log("Loading Jolibox SDK..."),this.testMode=e!=null?e:!1,this.loaderMetadata=o!=null?o:this.computeLoaderMetaData(),this.loadScript(),this.fetchUpdateLoaderMetadata(),console.log("Jolibox SDK loaded.")}get apiBaseURL(){return this.testMode?"https://test-api.jolibox.com":"https://api.jolibox.com"}get currentVersion(){return window.__JOLIBOX_LOCAL_SDK_VERSION__}get defaultMetadata(){let e=this.currentVersion;return{version:e,asyncScriptUrl:`https://cdn.jsdelivr.net/npm/@jolibox/web-async-sdk@${e}/dist/index.iife.js`}}};window.JoliboxSDKLoader=x;var b=class{constructor(){this.init=e=>{window.joliboxsdk._commandPipe.push({cmd:"ads.init",params:e})};this.adConfig=e=>{window.joliboxsdk._commandPipe.push({cmd:"ads.adConfig",params:e})};this.adBreak=e=>{window.joliboxsdk._commandPipe.push({cmd:"ads.adBreak",params:e})};this.adUnit=e=>p(this,null,function*(){window.joliboxsdk._commandPipe.push({cmd:"ads.adUnit",params:e})})}};window.JoliboxAds=b;var R=require("@jolibox/web-sync-sdk");window.__JOLIBOX_LOCAL_SDK_VERSION__="0.0.7";var c=class{constructor({useRuntimeSDK:e=!0,loaderConfig:o}={}){var r,a,n;e&&window.joliboxsdk?(this.loader=(r=window.joliboxsdk.loader)!=null?r:new window.JoliboxSDKLoader(o),this.ads=(a=window.joliboxsdk.ads)!=null?a:new window.JoliboxAds,this.runtime=(n=window.joliboxsdk.runtime)!=null?n:new window.JoliboxRuntime):(this.loader=new window.JoliboxSDKLoader(o),this.ads=new window.JoliboxAds,this.runtime=new window.JoliboxRuntime,window.joliboxsdk=Object.assign(this,{_commandPipe:[]},window.joliboxsdk)),window.joliboxsdk._commandPipe||(window.joliboxsdk._commandPipe=[])}};window.JoliboxSDK||(window.JoliboxSDK=c);var L=c;0&&(module.exports={JoliboxSDK});
2
- //# sourceMappingURL=index.cjs.map