@adlad/plugin-viverse 0.8.0 → 0.10.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.
package/deno.lock CHANGED
@@ -23,8 +23,8 @@
23
23
  "@jridgewell/trace-mapping"
24
24
  ]
25
25
  },
26
- "@jridgewell/sourcemap-codec@1.5.5": {
27
- "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="
26
+ "@jridgewell/sourcemap-codec@1.6.0": {
27
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="
28
28
  },
29
29
  "@jridgewell/trace-mapping@0.3.31": {
30
30
  "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
@@ -33,8 +33,8 @@
33
33
  "@jridgewell/sourcemap-codec"
34
34
  ]
35
35
  },
36
- "acorn@8.16.0": {
37
- "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
36
+ "acorn@8.19.0": {
37
+ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
38
38
  "bin": true
39
39
  },
40
40
  "buffer-from@1.1.2": {
@@ -107,7 +107,7 @@
107
107
  },
108
108
  "workspace": {
109
109
  "dependencies": [
110
- "npm:@adlad/adlad@1.0.0"
110
+ "npm:@adlad/adlad@1.1.0"
111
111
  ]
112
112
  }
113
113
  }
@@ -22,17 +22,13 @@ export function viversePlugin({ appId, }: {
22
22
  }): {
23
23
  readonly name: "viverse";
24
24
  readonly initialize: (ctx: any) => Promise<void>;
25
+ readonly manualNeedsMute: true;
26
+ readonly manualNeedsPause: true;
27
+ readonly showFullScreenAd: () => Promise<any>;
28
+ readonly showRewardedAd: () => Promise<any>;
29
+ readonly setStorageItem: (key: any, value: any) => Promise<void>;
30
+ readonly getStorageItem: (key: any) => Promise<any>;
25
31
  readonly customRequests: {
26
- /**
27
- * @param {string} key
28
- * @param {unknown} value
29
- */
30
- readonly setStorageItem: (key: string, value: unknown) => Promise<void>;
31
- /**
32
- * @param {string} key
33
- * @returns {Promise<unknown>}
34
- */
35
- readonly getStorageItem: (key: string) => Promise<unknown>;
36
32
  readonly showAuthPrompt: () => void;
37
33
  readonly getIsSignedIn: () => boolean;
38
34
  /**
@@ -1 +1 @@
1
- function viversePlugin({appId:e}){let t=!1;if(!e)throw new Error("No app id was provided");const a={viverse:"viverse",client:"client",clientId:"clientId",domain:"domain",cookieDomain:"cookieDomain",checkAuth:"checkAuth",loginWithWorlds:"loginWithWorlds",storage:"storage",newCloudSaveClient:"newCloudSaveClient",setPlayerData:"setPlayerData",getPlayerData:"getPlayerData",avatar:"avatar",baseURL:"baseURL",token:"token"};let i,o;a>0&&console.log(a);let n=null,s=null;const l=new Map,r="adlad_viverse_";return{name:"viverse",async initialize(s){if(t)throw new Error("Viverse plugin is being initialized more than once");if(t=!0,await s.loadScriptTag("https://www.viverse.com/static-assets/viverse-sdk/index.umd.cjs"),i=new globalThis[a.viverse][a.client]({[a.clientId]:e,[a.domain]:"account.htcvive.com",[a.cookieDomain]:window.location.hostname}),window.parent==window)throw new Error("The Viverse SDK is not supported unless the game is embedded on viverse.com.");const l=await i[a.checkAuth]();n=l?.access_token||null;const r=new globalThis[a.viverse][a.storage];o=await r[a.newCloudSaveClient](e)},customRequests:{async setStorageItem(e,t){const i=JSON.stringify(t);if(n)await o[a.setPlayerData](e,{s:i},n);else{await new Promise((e=>setTimeout(e,1e3)));try{localStorage.setItem(r+e,i)}catch{l.set(e,i)}}},async getStorageItem(e){let t;if(n){const i=await o[a.getPlayerData](e,n);t="object"==typeof i&&null!=i?i.s:null}else{await new Promise((e=>setTimeout(e,1e3)));try{t=localStorage.getItem(r+e)}catch{t=l.get(e)}}return t&&"string"==typeof t?JSON.parse(t):null},showAuthPrompt(){i[a.loginWithWorlds]()},getIsSignedIn:()=>Boolean(n),async getProfile(){const e=n?(s||(s=new viverse[a.avatar]({[a.baseURL]:"https://sdk-api.viverse.com/",[a.token]:n})),s):null;return e?await e.getProfile():null}}}}export{viversePlugin as default,viversePlugin};
1
+ function viversePlugin({appId:e}){let t=!1;if(!e)throw new Error("No app id was provided");const o={viverse:"viverse",ViverseAdSDK:"ViverseAdSDK",init:"init",client:"client",appId:"appId",clientId:"clientId",domain:"domain",cookieDomain:"cookieDomain",checkAuth:"checkAuth",loginWithWorlds:"loginWithWorlds",storage:"storage",newCloudSaveClient:"newCloudSaveClient",setPlayerData:"setPlayerData",getPlayerData:"getPlayerData",avatar:"avatar",baseURL:"baseURL",token:"token",onBreakStart:"onBreakStart",onBreakEnd:"onBreakEnd",onAdError:"onAdError",onRewardGranted:"onRewardGranted",showRewardVideo:"showRewardVideo",showVideo:"showVideo"};let a;o>0&&console.log(o);let n,r=null,s=null,i=null;const d=new Map,l="adlad_viverse_";let c=null;async function w(e=!1){if(!c)return{didShowAd:!1,errorReason:"unknown"};const t=c;if(!r)return{didShowAd:!1,errorReason:"not-supported"};let a;const n=new Promise((e=>{a=e}));function s(e){console.error(e);let t="unknown";return e instanceof Error&&e.message.includes("COOLDOWN_ACTIVE")&&(t="time-constraint"),{didShowAd:!1,errorReason:t}}try{const n={[o.onBreakStart]:()=>{t.setNeedsMute(!0),t.setNeedsPause(!0)},[o.onBreakEnd]:()=>{t.setNeedsMute(!1),t.setNeedsPause(!1),e||a({didShowAd:!0,errorReason:null})},[o.onAdError]:e=>{t.setNeedsMute(!1),t.setNeedsPause(!1),a(s(e))}};if(e){const e={...n,[o.onRewardGranted]:()=>{a({didShowAd:!0,errorReason:null})}};r[o.showRewardVideo](e)}else r[o.showVideo](n)}catch(e){return s(e)}return n}let u=performance.now();return{name:"viverse",async initialize(i){if(t)throw new Error("Viverse plugin is being initialized more than once");if(t=!0,c=i,await i.loadScriptTag("https://www.viverse.com/static-assets/viverse-sdk/index.umd.cjs"),a=new globalThis[o.viverse][o.client]({[o.clientId]:e,[o.domain]:"account.htcvive.com",[o.cookieDomain]:window.location.hostname}),window.parent==window)throw new Error("The Viverse SDK is not supported unless the game is embedded on viverse.com.");const d=await a[o.checkAuth]();s=d?.access_token||null;const l=new globalThis[o.viverse][o.storage];n=await l[o.newCloudSaveClient](e);try{await i.loadScriptTag("https://www.viverse.com/static-assets/viverse-ad-sdk/0.0.6/viverse-ad-sdk.umd.js");const t=globalThis[o.ViverseAdSDK];await t[o.init]({[o.appId]:e}),r=t}catch(e){i.setCanShowFullScreenAd(!1),i.setCanShowRewardedAd(!1),console.error(e)}u=performance.now()},manualNeedsMute:!0,manualNeedsPause:!0,showFullScreenAd:async()=>performance.now()-u<3e4?{didShowAd:!1,errorReason:"time-constraint"}:await w(!1),showRewardedAd:async()=>await w(!0),async setStorageItem(e,t){const a=JSON.stringify(t);if(s)await n[o.setPlayerData](e,{s:a},s);else{await new Promise((e=>setTimeout(e,1e3)));try{localStorage.setItem(l+e,a)}catch{d.set(e,a)}}},async getStorageItem(e){let t;if(s){const a=await n[o.getPlayerData](e,s);t="object"==typeof a&&null!=a?a.s:null}else{await new Promise((e=>setTimeout(e,1e3)));try{t=localStorage.getItem(l+e)}catch{t=d.get(e)}}return t&&"string"==typeof t?JSON.parse(t):null},customRequests:{showAuthPrompt(){a[o.loginWithWorlds]()},getIsSignedIn:()=>Boolean(s),async getProfile(){const e=s?(i||(i=new viverse[o.avatar]({[o.baseURL]:"https://sdk-api.viverse.com/",[o.token]:s})),i):null;return e?await e.getProfile():null}}}}export{viversePlugin as default,viversePlugin};
package/importmap.json CHANGED
@@ -2,6 +2,6 @@
2
2
  "imports": {
3
3
  "$std/": "https://deno.land/std@0.178.0/",
4
4
  "$chdir_anywhere": "https://deno.land/x/chdir_anywhere@v0.0.2/mod.js",
5
- "$adlad": "npm:@adlad/adlad@1.0.0"
5
+ "$adlad": "npm:@adlad/adlad@1.1.0"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adlad/plugin-viverse",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "AdLad plugin for the Viverse sdk.",
5
5
  "type": "module",
6
6
  "main": "mod.js",
package/src/mod.js CHANGED
@@ -30,7 +30,10 @@ export function viversePlugin({
30
30
 
31
31
  const props = /** @type {const} */ ({
32
32
  viverse: "viverse",
33
+ ViverseAdSDK: "ViverseAdSDK",
34
+ init: "init",
33
35
  client: "client",
36
+ appId: "appId",
34
37
  clientId: "clientId",
35
38
  domain: "domain",
36
39
  cookieDomain: "cookieDomain",
@@ -43,6 +46,12 @@ export function viversePlugin({
43
46
  avatar: "avatar",
44
47
  baseURL: "baseURL",
45
48
  token: "token",
49
+ onBreakStart: "onBreakStart",
50
+ onBreakEnd: "onBreakEnd",
51
+ onAdError: "onAdError",
52
+ onRewardGranted: "onRewardGranted",
53
+ showRewardVideo: "showRewardVideo",
54
+ showVideo: "showVideo",
46
55
  });
47
56
 
48
57
  // @ts-ignore We want to make sure that `props` remains an object.
@@ -57,6 +66,8 @@ export function viversePlugin({
57
66
 
58
67
  /** @type {import("./types.d.ts").ViverseClient} */
59
68
  let client;
69
+ /** @type {import("./types.d.ts").ViverseAdClient?} */
70
+ let adClient = null;
60
71
  /** @type {import("./types.d.ts").CloudSaveClient} */
61
72
  let cloudSaveClient;
62
73
  /** @type {string?} */
@@ -82,6 +93,98 @@ export function viversePlugin({
82
93
  // We add a prefix to localStorage keys to prevent clashes with manual calls to localStorage.setItem();
83
94
  const localStoragePrefix = "adlad_viverse_";
84
95
 
96
+ /** @type {import("$adlad").AdLadPluginInitializeContext?} */
97
+ let adladCtx = null;
98
+
99
+ /**
100
+ * @returns {Promise<import("$adlad").ShowFullScreenAdResult>}
101
+ */
102
+ async function showAd(isRewarded = false) {
103
+ if (!adladCtx) {
104
+ return {
105
+ didShowAd: false,
106
+ errorReason: "unknown",
107
+ };
108
+ }
109
+ const ctx = adladCtx;
110
+ if (!adClient) {
111
+ return {
112
+ didShowAd: false,
113
+ errorReason: "not-supported",
114
+ };
115
+ }
116
+ /** @type {(result: import("$adlad").ShowFullScreenAdResult) => void} */
117
+ let resolvePromise;
118
+ /** @type {Promise<import("$adlad").ShowFullScreenAdResult>} */
119
+ const promise = new Promise((resolve) => {
120
+ resolvePromise = resolve;
121
+ });
122
+
123
+ /**
124
+ * @param {unknown} error
125
+ * @returns {import("$adlad").ShowFullScreenAdResult}
126
+ */
127
+ function handleError(error) {
128
+ console.error(error);
129
+
130
+ /** @type {import("$adlad").AdErrorReason} */
131
+ let errorReason = "unknown";
132
+ if (error instanceof Error) {
133
+ if (error.message.includes("COOLDOWN_ACTIVE")) {
134
+ errorReason = "time-constraint";
135
+ }
136
+ }
137
+ return {
138
+ didShowAd: false,
139
+ errorReason,
140
+ };
141
+ }
142
+ try {
143
+ /** @type {import("./types.d.ts").ShowAdCallbacks} */
144
+ const callbacks = {
145
+ [props.onBreakStart]: () => {
146
+ ctx.setNeedsMute(true);
147
+ ctx.setNeedsPause(true);
148
+ },
149
+ [props.onBreakEnd]: () => {
150
+ ctx.setNeedsMute(false);
151
+ ctx.setNeedsPause(false);
152
+ if (!isRewarded) {
153
+ resolvePromise({
154
+ didShowAd: true,
155
+ errorReason: null,
156
+ });
157
+ }
158
+ },
159
+ [props.onAdError]: (error) => {
160
+ ctx.setNeedsMute(false);
161
+ ctx.setNeedsPause(false);
162
+ resolvePromise(handleError(error));
163
+ },
164
+ };
165
+ if (isRewarded) {
166
+ /** @type {import("./types.d.ts").ShowRewardedCallbacks} */
167
+ const rewardCallbacks = {
168
+ ...callbacks,
169
+ [props.onRewardGranted]: () => {
170
+ resolvePromise({
171
+ didShowAd: true,
172
+ errorReason: null,
173
+ });
174
+ },
175
+ };
176
+ adClient[props.showRewardVideo](rewardCallbacks);
177
+ } else {
178
+ adClient[props.showVideo](callbacks);
179
+ }
180
+ } catch (error) {
181
+ return handleError(error);
182
+ }
183
+ return promise;
184
+ }
185
+
186
+ let initializeTime = performance.now();
187
+
85
188
  const plugin = /** @type {const} @satisfies {import("$adlad").AdLadPlugin} */ ({
86
189
  name: "viverse",
87
190
  async initialize(ctx) {
@@ -90,6 +193,8 @@ export function viversePlugin({
90
193
  }
91
194
  initializeCalled = true;
92
195
 
196
+ adladCtx = ctx;
197
+
93
198
  await ctx.loadScriptTag("https://www.viverse.com/static-assets/viverse-sdk/index.umd.cjs");
94
199
 
95
200
  client = new globalThis[props.viverse][props.client]({
@@ -110,62 +215,87 @@ export function viversePlugin({
110
215
 
111
216
  const storageClient = new globalThis[props.viverse][props.storage]();
112
217
  cloudSaveClient = await storageClient[props.newCloudSaveClient](appId);
218
+
219
+ try {
220
+ await ctx.loadScriptTag(
221
+ "https://www.viverse.com/static-assets/viverse-ad-sdk/0.0.6/viverse-ad-sdk.umd.js",
222
+ );
223
+ const ads = globalThis[props.ViverseAdSDK];
224
+ await ads[props.init]({
225
+ [props.appId]: appId,
226
+ });
227
+ adClient = ads;
228
+ } catch (error) {
229
+ ctx.setCanShowFullScreenAd(false);
230
+ ctx.setCanShowRewardedAd(false);
231
+ console.error(error);
232
+ }
233
+ initializeTime = performance.now();
113
234
  },
114
- customRequests: {
115
- /**
116
- * @param {string} key
117
- * @param {unknown} value
118
- */
119
- async setStorageItem(key, value) {
120
- // The Viverse SDK doesn't allow passing raw values such as `true` or `42`,
121
- // but since this is quite common, we'll add support for this by stringifying the provided value.
122
- // This does mean the SDK will probably stringify it a second time, but oh well.
123
- const stringifiedValue = JSON.stringify(value);
124
- if (accessToken) {
125
- // If you give the viverse sdk a json string as input, the sdk will try to parse it.
126
- // This is rather unexpected however, because if a develoepr calls `setStorageItem("foo", "42")`,
127
- // they expect to get exactly `"42"` back when calling `getStorageItem("foo")`.
128
- // So in order to prevent the sdk from parsing our strings, we'll just provide an object.
129
- await cloudSaveClient[props.setPlayerData](key, { s: stringifiedValue }, accessToken);
130
- } else {
131
- // Calls to the viverse sdk normally do not resolve instantly, which might cause bugs in the application.
132
- // Let's simulate this behavior so it's easier to reproduce these issues in local development.
133
- await new Promise((resolve) => setTimeout(resolve, 1000));
134
- try {
135
- localStorage.setItem(localStoragePrefix + key, stringifiedValue);
136
- } catch {
137
- // The user is probably using private browsing, we'll fallback to session storage
138
- sessionStorage.set(key, stringifiedValue);
139
- }
235
+ manualNeedsMute: true,
236
+ manualNeedsPause: true,
237
+ async showFullScreenAd() {
238
+ if (performance.now() - initializeTime < 30_000) {
239
+ // Viverse doesn't allow us to show ads when the game starts (and in fact, it seems like showing
240
+ // ads at the start causes the player to get stuck), so we add a timeout of 30 seconds after initialization
241
+ // to avoid showing ads at the start
242
+ return {
243
+ didShowAd: false,
244
+ errorReason: "time-constraint",
245
+ };
246
+ }
247
+ return await showAd(false);
248
+ },
249
+ async showRewardedAd() {
250
+ return await showAd(true);
251
+ },
252
+ async setStorageItem(key, value) {
253
+ // The Viverse SDK doesn't allow passing raw values such as `true` or `42`,
254
+ // but since this is quite common, we'll add support for this by stringifying the provided value.
255
+ // This does mean the SDK will probably stringify it a second time, but oh well.
256
+ const stringifiedValue = JSON.stringify(value);
257
+ if (accessToken) {
258
+ // If you give the viverse sdk a json string as input, the sdk will try to parse it.
259
+ // This is rather unexpected however, because if a develoepr calls `setStorageItem("foo", "42")`,
260
+ // they expect to get exactly `"42"` back when calling `getStorageItem("foo")`.
261
+ // So in order to prevent the sdk from parsing our strings, we'll just provide an object.
262
+ await cloudSaveClient[props.setPlayerData](key, { s: stringifiedValue }, accessToken);
263
+ } else {
264
+ // Calls to the viverse sdk normally do not resolve instantly, which might cause bugs in the application.
265
+ // Let's simulate this behavior so it's easier to reproduce these issues in local development.
266
+ await new Promise((resolve) => setTimeout(resolve, 1000));
267
+ try {
268
+ localStorage.setItem(localStoragePrefix + key, stringifiedValue);
269
+ } catch {
270
+ // The user is probably using private browsing, we'll fallback to session storage
271
+ sessionStorage.set(key, stringifiedValue);
140
272
  }
141
- },
142
- /**
143
- * @param {string} key
144
- * @returns {Promise<unknown>}
145
- */
146
- async getStorageItem(key) {
147
- let stringifiedValue;
148
- if (accessToken) {
149
- const objectifiedValue =
150
- /** @type {{s: string}} */ (await cloudSaveClient[props.getPlayerData](key, accessToken));
151
- if (typeof objectifiedValue == "object" && objectifiedValue != null) {
152
- stringifiedValue = objectifiedValue.s;
153
- } else {
154
- stringifiedValue = null;
155
- }
273
+ }
274
+ },
275
+ async getStorageItem(key) {
276
+ let stringifiedValue;
277
+ if (accessToken) {
278
+ const objectifiedValue =
279
+ /** @type {{s: string}} */ (await cloudSaveClient[props.getPlayerData](key, accessToken));
280
+ if (typeof objectifiedValue == "object" && objectifiedValue != null) {
281
+ stringifiedValue = objectifiedValue.s;
156
282
  } else {
157
- // Calls to the viverse sdk normally do not resolve instantly, which might cause bugs in the application.
158
- // Let's simulate this behavior so it's easier to reproduce these issues in local development.
159
- await new Promise((resolve) => setTimeout(resolve, 1000));
160
- try {
161
- stringifiedValue = localStorage.getItem(localStoragePrefix + key);
162
- } catch {
163
- stringifiedValue = sessionStorage.get(key);
164
- }
283
+ stringifiedValue = null;
165
284
  }
166
- if (!stringifiedValue || typeof stringifiedValue != "string") return null;
167
- return JSON.parse(stringifiedValue);
168
- },
285
+ } else {
286
+ // Calls to the viverse sdk normally do not resolve instantly, which might cause bugs in the application.
287
+ // Let's simulate this behavior so it's easier to reproduce these issues in local development.
288
+ await new Promise((resolve) => setTimeout(resolve, 1000));
289
+ try {
290
+ stringifiedValue = localStorage.getItem(localStoragePrefix + key);
291
+ } catch {
292
+ stringifiedValue = sessionStorage.get(key);
293
+ }
294
+ }
295
+ if (!stringifiedValue || typeof stringifiedValue != "string") return null;
296
+ return JSON.parse(stringifiedValue);
297
+ },
298
+ customRequests: {
169
299
  showAuthPrompt() {
170
300
  client[props.loginWithWorlds]();
171
301
  },
package/src/types.d.ts CHANGED
@@ -6,6 +6,7 @@ declare global {
6
6
  storage: typeof ViverseStorage;
7
7
  avatar: typeof ViverseAvatarClient;
8
8
  };
9
+ var ViverseAdSDK: ViverseAdClient;
9
10
  }
10
11
 
11
12
  interface ViverseClientOptions {
@@ -47,4 +48,29 @@ export class ViverseAvatarClient {
47
48
  getProfile(): Promise<ViverseProfile>;
48
49
  }
49
50
 
51
+ interface ViverseAdClientOptions {
52
+ appId: string;
53
+ }
54
+
55
+ export interface ShowAdCallbacks {
56
+ onBreakStart: () => void;
57
+ onBreakEnd: () => void;
58
+ onAdError: (error: unknown) => void;
59
+ }
60
+
61
+ export interface ShowRewardedCallbacks {
62
+ onBreakStart: () => void;
63
+ onBreakEnd: () => void;
64
+ onRewardGranted: () => void;
65
+ onAdError: (error: unknown) => void;
66
+ }
67
+
68
+ export class ViverseAdClient {
69
+ init(options: ViverseAdClientOptions): Promise<void>;
70
+ showOverlay(options: ShowAdCallbacks): void;
71
+ showVideo(options: ShowAdCallbacks): void;
72
+ showRewardOverlay(options: ShowRewardedCallbacks): void;
73
+ showRewardVideo(options: ShowRewardedCallbacks): void;
74
+ }
75
+
50
76
  export {};