MCPcopy
hub / github.com/ionic-team/capacitor / registerPlugin

Function registerPlugin

core/src/runtime.ts:50–192  ·  view source on GitHub ↗
(pluginName: string, jsImplementations: PluginImplementations = {})

Source from the content-addressed store, hash-verified

48 const registeredPlugins = new Map<string, RegisteredPlugin>();
49
50 const registerPlugin = (pluginName: string, jsImplementations: PluginImplementations = {}): any => {
51 const registeredPlugin = registeredPlugins.get(pluginName);
52 if (registeredPlugin) {
53 console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
54
55 return registeredPlugin.proxy;
56 }
57
58 const platform = getPlatform();
59 const pluginHeader = getPluginHeader(pluginName);
60 let jsImplementation: any;
61
62 const loadPluginImplementation = async (): Promise<any> => {
63 if (!jsImplementation && platform in jsImplementations) {
64 jsImplementation =
65 typeof jsImplementations[platform] === 'function'
66 ? (jsImplementation = await jsImplementations[platform]())
67 : (jsImplementation = jsImplementations[platform]);
68 } else if (capCustomPlatform !== null && !jsImplementation && 'web' in jsImplementations) {
69 jsImplementation =
70 typeof jsImplementations['web'] === 'function'
71 ? (jsImplementation = await jsImplementations['web']())
72 : (jsImplementation = jsImplementations['web']);
73 }
74
75 return jsImplementation;
76 };
77
78 const createPluginMethod = (impl: any, prop: PropertyKey): ((...args: any[]) => any) => {
79 if (pluginHeader) {
80 const methodHeader = pluginHeader?.methods.find((m) => prop === m.name);
81 if (methodHeader) {
82 if (methodHeader.rtype === 'promise') {
83 return (options: any) => cap.nativePromise(pluginName, prop.toString(), options);
84 } else {
85 return (options: any, callback: any) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
86 }
87 } else if (impl) {
88 return impl[prop]?.bind(impl);
89 }
90 } else if (impl) {
91 return impl[prop]?.bind(impl);
92 } else {
93 throw new CapacitorException(
94 `"${pluginName}" plugin is not implemented on ${platform}`,
95 ExceptionCode.Unimplemented,
96 );
97 }
98 };
99
100 const createPluginMethodWrapper = (prop: PropertyKey) => {
101 let remove: (() => void) | undefined;
102 const wrapper = (...args: any[]) => {
103 const p = loadPluginImplementation().then((impl) => {
104 const fn = createPluginMethod(impl, prop);
105
106 if (fn) {
107 const p = fn(...args);

Callers 1

core-plugins.tsFile · 0.85

Calls 5

getPluginHeaderFunction · 0.85
warnMethod · 0.80
getPlatformFunction · 0.70
getMethod · 0.65

Tested by

no test coverage detected