UNPKG

17.7 kBJavaScriptView Raw
1/*! Capacitor: https://capacitorjs.com/ - MIT License */
2'use strict';
3
4Object.defineProperty(exports, '__esModule', { value: true });
5
6const createCapacitorPlatforms = (win) => {
7 const defaultPlatformMap = new Map();
8 defaultPlatformMap.set('web', { name: 'web' });
9 const capPlatforms = win.CapacitorPlatforms || {
10 currentPlatform: { name: 'web' },
11 platforms: defaultPlatformMap,
12 };
13 const addPlatform = (name, platform) => {
14 capPlatforms.platforms.set(name, platform);
15 };
16 const setPlatform = (name) => {
17 if (capPlatforms.platforms.has(name)) {
18 capPlatforms.currentPlatform = capPlatforms.platforms.get(name);
19 }
20 };
21 capPlatforms.addPlatform = addPlatform;
22 capPlatforms.setPlatform = setPlatform;
23 return capPlatforms;
24};
25const initPlatforms = (win) => (win.CapacitorPlatforms = createCapacitorPlatforms(win));
26/**
27 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
28 */
29const CapacitorPlatforms = /*#__PURE__*/ initPlatforms((typeof globalThis !== 'undefined'
30 ? globalThis
31 : typeof self !== 'undefined'
32 ? self
33 : typeof window !== 'undefined'
34 ? window
35 : typeof global !== 'undefined'
36 ? global
37 : {}));
38/**
39 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
40 */
41const addPlatform = CapacitorPlatforms.addPlatform;
42/**
43 * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead
44 */
45const setPlatform = CapacitorPlatforms.setPlatform;
46
47const legacyRegisterWebPlugin = (cap, webPlugin) => {
48 var _a;
49 const config = webPlugin.config;
50 const Plugins = cap.Plugins;
51 if (!config || !config.name) {
52 // TODO: add link to upgrade guide
53 throw new Error(`Capacitor WebPlugin is using the deprecated "registerWebPlugin()" function, but without the config. Please use "registerPlugin()" instead to register this web plugin."`);
54 }
55 // TODO: add link to upgrade guide
56 console.warn(`Capacitor plugin "${config.name}" is using the deprecated "registerWebPlugin()" function`);
57 if (!Plugins[config.name] || ((_a = config === null || config === void 0 ? void 0 : config.platforms) === null || _a === void 0 ? void 0 : _a.includes(cap.getPlatform()))) {
58 // Add the web plugin into the plugins registry if there already isn't
59 // an existing one. If it doesn't already exist, that means
60 // there's no existing native implementation for it.
61 // - OR -
62 // If we already have a plugin registered (meaning it was defined in the native layer),
63 // then we should only overwrite it if the corresponding web plugin activates on
64 // a certain platform. For example: Geolocation uses the WebPlugin on Android but not iOS
65 Plugins[config.name] = webPlugin;
66 }
67};
68
69exports.ExceptionCode = void 0;
70(function (ExceptionCode) {
71 /**
72 * API is not implemented.
73 *
74 * This usually means the API can't be used because it is not implemented for
75 * the current platform.
76 */
77 ExceptionCode["Unimplemented"] = "UNIMPLEMENTED";
78 /**
79 * API is not available.
80 *
81 * This means the API can't be used right now because:
82 * - it is currently missing a prerequisite, such as network connectivity
83 * - it requires a particular platform or browser version
84 */
85 ExceptionCode["Unavailable"] = "UNAVAILABLE";
86})(exports.ExceptionCode || (exports.ExceptionCode = {}));
87class CapacitorException extends Error {
88 constructor(message, code) {
89 super(message);
90 this.message = message;
91 this.code = code;
92 }
93}
94const getPlatformId = (win) => {
95 var _a, _b;
96 if (win === null || win === void 0 ? void 0 : win.androidBridge) {
97 return 'android';
98 }
99 else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
100 return 'ios';
101 }
102 else {
103 return 'web';
104 }
105};
106
107const createCapacitor = (win) => {
108 var _a, _b, _c, _d, _e;
109 const capCustomPlatform = win.CapacitorCustomPlatform || null;
110 const cap = win.Capacitor || {};
111 const Plugins = (cap.Plugins = cap.Plugins || {});
112 /**
113 * @deprecated Use `capCustomPlatform` instead, default functions like registerPlugin will function with the new object.
114 */
115 const capPlatforms = win.CapacitorPlatforms;
116 const defaultGetPlatform = () => {
117 return capCustomPlatform !== null
118 ? capCustomPlatform.name
119 : getPlatformId(win);
120 };
121 const getPlatform = ((_a = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _a === void 0 ? void 0 : _a.getPlatform) || defaultGetPlatform;
122 const defaultIsNativePlatform = () => getPlatform() !== 'web';
123 const isNativePlatform = ((_b = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _b === void 0 ? void 0 : _b.isNativePlatform) || defaultIsNativePlatform;
124 const defaultIsPluginAvailable = (pluginName) => {
125 const plugin = registeredPlugins.get(pluginName);
126 if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {
127 // JS implementation available for the current platform.
128 return true;
129 }
130 if (getPluginHeader(pluginName)) {
131 // Native implementation available.
132 return true;
133 }
134 return false;
135 };
136 const isPluginAvailable = ((_c = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _c === void 0 ? void 0 : _c.isPluginAvailable) ||
137 defaultIsPluginAvailable;
138 const defaultGetPluginHeader = (pluginName) => { var _a; return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find(h => h.name === pluginName); };
139 const getPluginHeader = ((_d = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _d === void 0 ? void 0 : _d.getPluginHeader) || defaultGetPluginHeader;
140 const handleError = (err) => win.console.error(err);
141 const pluginMethodNoop = (_target, prop, pluginName) => {
142 return Promise.reject(`${pluginName} does not have an implementation of "${prop}".`);
143 };
144 const registeredPlugins = new Map();
145 const defaultRegisterPlugin = (pluginName, jsImplementations = {}) => {
146 const registeredPlugin = registeredPlugins.get(pluginName);
147 if (registeredPlugin) {
148 console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
149 return registeredPlugin.proxy;
150 }
151 const platform = getPlatform();
152 const pluginHeader = getPluginHeader(pluginName);
153 let jsImplementation;
154 const loadPluginImplementation = async () => {
155 if (!jsImplementation && platform in jsImplementations) {
156 jsImplementation =
157 typeof jsImplementations[platform] === 'function'
158 ? (jsImplementation = await jsImplementations[platform]())
159 : (jsImplementation = jsImplementations[platform]);
160 }
161 else if (capCustomPlatform !== null &&
162 !jsImplementation &&
163 'web' in jsImplementations) {
164 jsImplementation =
165 typeof jsImplementations['web'] === 'function'
166 ? (jsImplementation = await jsImplementations['web']())
167 : (jsImplementation = jsImplementations['web']);
168 }
169 return jsImplementation;
170 };
171 const createPluginMethod = (impl, prop) => {
172 var _a, _b;
173 if (pluginHeader) {
174 const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find(m => prop === m.name);
175 if (methodHeader) {
176 if (methodHeader.rtype === 'promise') {
177 return (options) => cap.nativePromise(pluginName, prop.toString(), options);
178 }
179 else {
180 return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
181 }
182 }
183 else if (impl) {
184 return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);
185 }
186 }
187 else if (impl) {
188 return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);
189 }
190 else {
191 throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, exports.ExceptionCode.Unimplemented);
192 }
193 };
194 const createPluginMethodWrapper = (prop) => {
195 let remove;
196 const wrapper = (...args) => {
197 const p = loadPluginImplementation().then(impl => {
198 const fn = createPluginMethod(impl, prop);
199 if (fn) {
200 const p = fn(...args);
201 remove = p === null || p === void 0 ? void 0 : p.remove;
202 return p;
203 }
204 else {
205 throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, exports.ExceptionCode.Unimplemented);
206 }
207 });
208 if (prop === 'addListener') {
209 p.remove = async () => remove();
210 }
211 return p;
212 };
213 // Some flair ✨
214 wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
215 Object.defineProperty(wrapper, 'name', {
216 value: prop,
217 writable: false,
218 configurable: false,
219 });
220 return wrapper;
221 };
222 const addListener = createPluginMethodWrapper('addListener');
223 const removeListener = createPluginMethodWrapper('removeListener');
224 const addListenerNative = (eventName, callback) => {
225 const call = addListener({ eventName }, callback);
226 const remove = async () => {
227 const callbackId = await call;
228 removeListener({
229 eventName,
230 callbackId,
231 }, callback);
232 };
233 const p = new Promise(resolve => call.then(() => resolve({ remove })));
234 p.remove = async () => {
235 console.warn(`Using addListener() without 'await' is deprecated.`);
236 await remove();
237 };
238 return p;
239 };
240 const proxy = new Proxy({}, {
241 get(_, prop) {
242 switch (prop) {
243 // https://github.com/facebook/react/issues/20030
244 case '$$typeof':
245 return undefined;
246 case 'toJSON':
247 return () => ({});
248 case 'addListener':
249 return pluginHeader ? addListenerNative : addListener;
250 case 'removeListener':
251 return removeListener;
252 default:
253 return createPluginMethodWrapper(prop);
254 }
255 },
256 });
257 Plugins[pluginName] = proxy;
258 registeredPlugins.set(pluginName, {
259 name: pluginName,
260 proxy,
261 platforms: new Set([
262 ...Object.keys(jsImplementations),
263 ...(pluginHeader ? [platform] : []),
264 ]),
265 });
266 return proxy;
267 };
268 const registerPlugin = ((_e = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _e === void 0 ? void 0 : _e.registerPlugin) || defaultRegisterPlugin;
269 // Add in convertFileSrc for web, it will already be available in native context
270 if (!cap.convertFileSrc) {
271 cap.convertFileSrc = filePath => filePath;
272 }
273 cap.getPlatform = getPlatform;
274 cap.handleError = handleError;
275 cap.isNativePlatform = isNativePlatform;
276 cap.isPluginAvailable = isPluginAvailable;
277 cap.pluginMethodNoop = pluginMethodNoop;
278 cap.registerPlugin = registerPlugin;
279 cap.Exception = CapacitorException;
280 cap.DEBUG = !!cap.DEBUG;
281 cap.isLoggingEnabled = !!cap.isLoggingEnabled;
282 // Deprecated props
283 cap.platform = cap.getPlatform();
284 cap.isNative = cap.isNativePlatform();
285 return cap;
286};
287const initCapacitorGlobal = (win) => (win.Capacitor = createCapacitor(win));
288
289const Capacitor = /*#__PURE__*/ initCapacitorGlobal(typeof globalThis !== 'undefined'
290 ? globalThis
291 : typeof self !== 'undefined'
292 ? self
293 : typeof window !== 'undefined'
294 ? window
295 : typeof global !== 'undefined'
296 ? global
297 : {});
298const registerPlugin = Capacitor.registerPlugin;
299/**
300 * @deprecated Provided for backwards compatibility for Capacitor v2 plugins.
301 * Capacitor v3 plugins should import the plugin directly. This "Plugins"
302 * export is deprecated in v3, and will be removed in v4.
303 */
304const Plugins = Capacitor.Plugins;
305/**
306 * Provided for backwards compatibility. Use the registerPlugin() API
307 * instead, and provide the web plugin as the "web" implmenetation.
308 * For example
309 *
310 * export const Example = registerPlugin('Example', {
311 * web: () => import('./web').then(m => new m.Example())
312 * })
313 *
314 * @deprecated Deprecated in v3, will be removed from v4.
315 */
316const registerWebPlugin = (plugin) => legacyRegisterWebPlugin(Capacitor, plugin);
317
318/**
319 * Base class web plugins should extend.
320 */
321class WebPlugin {
322 constructor(config) {
323 this.listeners = {};
324 this.windowListeners = {};
325 if (config) {
326 // TODO: add link to upgrade guide
327 console.warn(`Capacitor WebPlugin "${config.name}" config object was deprecated in v3 and will be removed in v4.`);
328 this.config = config;
329 }
330 }
331 addListener(eventName, listenerFunc) {
332 const listeners = this.listeners[eventName];
333 if (!listeners) {
334 this.listeners[eventName] = [];
335 }
336 this.listeners[eventName].push(listenerFunc);
337 // If we haven't added a window listener for this event and it requires one,
338 // go ahead and add it
339 const windowListener = this.windowListeners[eventName];
340 if (windowListener && !windowListener.registered) {
341 this.addWindowListener(windowListener);
342 }
343 const remove = async () => this.removeListener(eventName, listenerFunc);
344 const p = Promise.resolve({ remove });
345 Object.defineProperty(p, 'remove', {
346 value: async () => {
347 console.warn(`Using addListener() without 'await' is deprecated.`);
348 await remove();
349 },
350 });
351 return p;
352 }
353 async removeAllListeners() {
354 this.listeners = {};
355 for (const listener in this.windowListeners) {
356 this.removeWindowListener(this.windowListeners[listener]);
357 }
358 this.windowListeners = {};
359 }
360 notifyListeners(eventName, data) {
361 const listeners = this.listeners[eventName];
362 if (listeners) {
363 listeners.forEach(listener => listener(data));
364 }
365 }
366 hasListeners(eventName) {
367 return !!this.listeners[eventName].length;
368 }
369 registerWindowListener(windowEventName, pluginEventName) {
370 this.windowListeners[pluginEventName] = {
371 registered: false,
372 windowEventName,
373 pluginEventName,
374 handler: event => {
375 this.notifyListeners(pluginEventName, event);
376 },
377 };
378 }
379 unimplemented(msg = 'not implemented') {
380 return new Capacitor.Exception(msg, exports.ExceptionCode.Unimplemented);
381 }
382 unavailable(msg = 'not available') {
383 return new Capacitor.Exception(msg, exports.ExceptionCode.Unavailable);
384 }
385 async removeListener(eventName, listenerFunc) {
386 const listeners = this.listeners[eventName];
387 if (!listeners) {
388 return;
389 }
390 const index = listeners.indexOf(listenerFunc);
391 this.listeners[eventName].splice(index, 1);
392 // If there are no more listeners for this type of event,
393 // remove the window listener
394 if (!this.listeners[eventName].length) {
395 this.removeWindowListener(this.windowListeners[eventName]);
396 }
397 }
398 addWindowListener(handle) {
399 window.addEventListener(handle.windowEventName, handle.handler);
400 handle.registered = true;
401 }
402 removeWindowListener(handle) {
403 if (!handle) {
404 return;
405 }
406 window.removeEventListener(handle.windowEventName, handle.handler);
407 handle.registered = false;
408 }
409}
410
411const WebView = /*#__PURE__*/ registerPlugin('WebView');
412
413exports.Capacitor = Capacitor;
414exports.CapacitorException = CapacitorException;
415exports.CapacitorPlatforms = CapacitorPlatforms;
416exports.Plugins = Plugins;
417exports.WebPlugin = WebPlugin;
418exports.WebView = WebView;
419exports.addPlatform = addPlatform;
420exports.registerPlugin = registerPlugin;
421exports.registerWebPlugin = registerWebPlugin;
422exports.setPlatform = setPlatform;
423//# sourceMappingURL=index.cjs.js.map