@cappitolian/http-local-server 0.0.4 → 0.0.5

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/Package.swift CHANGED
@@ -10,7 +10,7 @@ let package = Package(
10
10
  targets: ["HttpLocalServerPlugin"])
11
11
  ],
12
12
  dependencies: [
13
- .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")
13
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "7.0.0")
14
14
  ],
15
15
  targets: [
16
16
  .target(
package/README.md CHANGED
@@ -13,25 +13,114 @@ npx cap sync
13
13
 
14
14
  <docgen-index>
15
15
 
16
- * [`echo(...)`](#echo)
16
+ * [`connect()`](#connect)
17
+ * [`disconnect()`](#disconnect)
18
+ * [`sendResponse(...)`](#sendresponse)
19
+ * [`addListener('onRequest', ...)`](#addlisteneronrequest-)
20
+ * [`removeAllListeners()`](#removealllisteners)
21
+ * [Interfaces](#interfaces)
17
22
 
18
23
  </docgen-index>
19
24
 
20
25
  <docgen-api>
21
26
  <!--Update the source file JSDoc comments and rerun docgen to update the docs below-->
22
27
 
23
- ### echo(...)
28
+ ### connect()
24
29
 
25
30
  ```typescript
26
- echo(options: { value: string; }) => Promise<{ value: string; }>
31
+ connect() => Promise<HttpConnectResult>
27
32
  ```
28
33
 
29
- | Param | Type |
30
- | ------------- | ------------------------------- |
31
- | **`options`** | <code>{ value: string; }</code> |
34
+ Inicia el servidor local en el dispositivo nativo.
35
+ Devuelve la IP y el puerto asignado.
32
36
 
33
- **Returns:** <code>Promise&lt;{ value: string; }&gt;</code>
37
+ **Returns:** <code>Promise&lt;<a href="#httpconnectresult">HttpConnectResult</a>&gt;</code>
34
38
 
35
39
  --------------------
36
40
 
41
+
42
+ ### disconnect()
43
+
44
+ ```typescript
45
+ disconnect() => Promise<void>
46
+ ```
47
+
48
+ Detiene el servidor local.
49
+
50
+ --------------------
51
+
52
+
53
+ ### sendResponse(...)
54
+
55
+ ```typescript
56
+ sendResponse(options: { requestId: string; body: string; }) => Promise<void>
57
+ ```
58
+
59
+ Envía la respuesta de vuelta al cliente que hizo la petición.
60
+ El requestId debe coincidir con el recibido en 'onRequest'.
61
+
62
+ | Param | Type |
63
+ | ------------- | ------------------------------------------------- |
64
+ | **`options`** | <code>{ requestId: string; body: string; }</code> |
65
+
66
+ --------------------
67
+
68
+
69
+ ### addListener('onRequest', ...)
70
+
71
+ ```typescript
72
+ addListener(eventName: 'onRequest', listenerFunc: (data: HttpRequestData) => void) => Promise<PluginListenerHandle>
73
+ ```
74
+
75
+ Escucha las peticiones HTTP entrantes.
76
+
77
+ | Param | Type |
78
+ | ------------------ | ------------------------------------------------------------------------------ |
79
+ | **`eventName`** | <code>'onRequest'</code> |
80
+ | **`listenerFunc`** | <code>(data: <a href="#httprequestdata">HttpRequestData</a>) =&gt; void</code> |
81
+
82
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
83
+
84
+ --------------------
85
+
86
+
87
+ ### removeAllListeners()
88
+
89
+ ```typescript
90
+ removeAllListeners() => Promise<void>
91
+ ```
92
+
93
+ Elimina todos los listeners registrados.
94
+
95
+ --------------------
96
+
97
+
98
+ ### Interfaces
99
+
100
+
101
+ #### HttpConnectResult
102
+
103
+ | Prop | Type |
104
+ | ---------- | ------------------- |
105
+ | **`ip`** | <code>string</code> |
106
+ | **`port`** | <code>number</code> |
107
+
108
+
109
+ #### PluginListenerHandle
110
+
111
+ | Prop | Type |
112
+ | ------------ | ----------------------------------------- |
113
+ | **`remove`** | <code>() =&gt; Promise&lt;void&gt;</code> |
114
+
115
+
116
+ #### HttpRequestData
117
+
118
+ | Prop | Type |
119
+ | --------------- | ------------------- |
120
+ | **`requestId`** | <code>string</code> |
121
+ | **`method`** | <code>string</code> |
122
+ | **`path`** | <code>string</code> |
123
+ | **`body`** | <code>string</code> |
124
+ | **`headers`** | <code>any</code> |
125
+
37
126
  </docgen-api>
package/dist/docs.json CHANGED
@@ -6,25 +6,165 @@
6
6
  "tags": [],
7
7
  "methods": [
8
8
  {
9
- "name": "echo",
10
- "signature": "(options: { value: string; }) => Promise<{ value: string; }>",
9
+ "name": "connect",
10
+ "signature": "() => Promise<HttpConnectResult>",
11
+ "parameters": [],
12
+ "returns": "Promise<HttpConnectResult>",
13
+ "tags": [],
14
+ "docs": "Inicia el servidor local en el dispositivo nativo.\nDevuelve la IP y el puerto asignado.",
15
+ "complexTypes": [
16
+ "HttpConnectResult"
17
+ ],
18
+ "slug": "connect"
19
+ },
20
+ {
21
+ "name": "disconnect",
22
+ "signature": "() => Promise<void>",
23
+ "parameters": [],
24
+ "returns": "Promise<void>",
25
+ "tags": [],
26
+ "docs": "Detiene el servidor local.",
27
+ "complexTypes": [],
28
+ "slug": "disconnect"
29
+ },
30
+ {
31
+ "name": "sendResponse",
32
+ "signature": "(options: { requestId: string; body: string; }) => Promise<void>",
11
33
  "parameters": [
12
34
  {
13
35
  "name": "options",
14
36
  "docs": "",
15
- "type": "{ value: string; }"
37
+ "type": "{ requestId: string; body: string; }"
16
38
  }
17
39
  ],
18
- "returns": "Promise<{ value: string; }>",
40
+ "returns": "Promise<void>",
41
+ "tags": [],
42
+ "docs": "Envía la respuesta de vuelta al cliente que hizo la petición.\nEl requestId debe coincidir con el recibido en 'onRequest'.",
43
+ "complexTypes": [],
44
+ "slug": "sendresponse"
45
+ },
46
+ {
47
+ "name": "addListener",
48
+ "signature": "(eventName: 'onRequest', listenerFunc: (data: HttpRequestData) => void) => Promise<PluginListenerHandle>",
49
+ "parameters": [
50
+ {
51
+ "name": "eventName",
52
+ "docs": "",
53
+ "type": "'onRequest'"
54
+ },
55
+ {
56
+ "name": "listenerFunc",
57
+ "docs": "",
58
+ "type": "(data: HttpRequestData) => void"
59
+ }
60
+ ],
61
+ "returns": "Promise<PluginListenerHandle>",
62
+ "tags": [],
63
+ "docs": "Escucha las peticiones HTTP entrantes.",
64
+ "complexTypes": [
65
+ "PluginListenerHandle",
66
+ "HttpRequestData"
67
+ ],
68
+ "slug": "addlisteneronrequest-"
69
+ },
70
+ {
71
+ "name": "removeAllListeners",
72
+ "signature": "() => Promise<void>",
73
+ "parameters": [],
74
+ "returns": "Promise<void>",
19
75
  "tags": [],
20
- "docs": "",
76
+ "docs": "Elimina todos los listeners registrados.",
21
77
  "complexTypes": [],
22
- "slug": "echo"
78
+ "slug": "removealllisteners"
23
79
  }
24
80
  ],
25
81
  "properties": []
26
82
  },
27
- "interfaces": [],
83
+ "interfaces": [
84
+ {
85
+ "name": "HttpConnectResult",
86
+ "slug": "httpconnectresult",
87
+ "docs": "",
88
+ "tags": [],
89
+ "methods": [],
90
+ "properties": [
91
+ {
92
+ "name": "ip",
93
+ "tags": [],
94
+ "docs": "",
95
+ "complexTypes": [],
96
+ "type": "string"
97
+ },
98
+ {
99
+ "name": "port",
100
+ "tags": [],
101
+ "docs": "",
102
+ "complexTypes": [],
103
+ "type": "number"
104
+ }
105
+ ]
106
+ },
107
+ {
108
+ "name": "PluginListenerHandle",
109
+ "slug": "pluginlistenerhandle",
110
+ "docs": "",
111
+ "tags": [],
112
+ "methods": [],
113
+ "properties": [
114
+ {
115
+ "name": "remove",
116
+ "tags": [],
117
+ "docs": "",
118
+ "complexTypes": [],
119
+ "type": "() => Promise<void>"
120
+ }
121
+ ]
122
+ },
123
+ {
124
+ "name": "HttpRequestData",
125
+ "slug": "httprequestdata",
126
+ "docs": "",
127
+ "tags": [],
128
+ "methods": [],
129
+ "properties": [
130
+ {
131
+ "name": "requestId",
132
+ "tags": [],
133
+ "docs": "",
134
+ "complexTypes": [],
135
+ "type": "string"
136
+ },
137
+ {
138
+ "name": "method",
139
+ "tags": [],
140
+ "docs": "",
141
+ "complexTypes": [],
142
+ "type": "string"
143
+ },
144
+ {
145
+ "name": "path",
146
+ "tags": [],
147
+ "docs": "",
148
+ "complexTypes": [],
149
+ "type": "string"
150
+ },
151
+ {
152
+ "name": "body",
153
+ "tags": [],
154
+ "docs": "",
155
+ "complexTypes": [],
156
+ "type": "string"
157
+ },
158
+ {
159
+ "name": "headers",
160
+ "tags": [],
161
+ "docs": "",
162
+ "complexTypes": [],
163
+ "type": "any"
164
+ }
165
+ ]
166
+ }
167
+ ],
28
168
  "enums": [],
29
169
  "typeAliases": [],
30
170
  "pluginConfigs": []
@@ -1,7 +1,39 @@
1
+ import type { PluginListenerHandle } from '@capacitor/core';
2
+ export interface HttpConnectResult {
3
+ ip: string;
4
+ port: number;
5
+ }
6
+ export interface HttpRequestData {
7
+ requestId: string;
8
+ method: string;
9
+ path: string;
10
+ body: string;
11
+ headers?: any;
12
+ }
1
13
  export interface HttpLocalServerPlugin {
2
- echo(options: {
3
- value: string;
4
- }): Promise<{
5
- value: string;
6
- }>;
14
+ /**
15
+ * Inicia el servidor local en el dispositivo nativo.
16
+ * Devuelve la IP y el puerto asignado.
17
+ */
18
+ connect(): Promise<HttpConnectResult>;
19
+ /**
20
+ * Detiene el servidor local.
21
+ */
22
+ disconnect(): Promise<void>;
23
+ /**
24
+ * Envía la respuesta de vuelta al cliente que hizo la petición.
25
+ * El requestId debe coincidir con el recibido en 'onRequest'.
26
+ */
27
+ sendResponse(options: {
28
+ requestId: string;
29
+ body: string;
30
+ }): Promise<void>;
31
+ /**
32
+ * Escucha las peticiones HTTP entrantes.
33
+ */
34
+ addListener(eventName: 'onRequest', listenerFunc: (data: HttpRequestData) => void): Promise<PluginListenerHandle>;
35
+ /**
36
+ * Elimina todos los listeners registrados.
37
+ */
38
+ removeAllListeners(): Promise<void>;
7
39
  }
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["export interface HttpLocalServerPlugin {\n echo(options: { value: string }): Promise<{ value: string }>;\n}\n"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport interface HttpConnectResult {\n ip: string;\n port: number;\n}\n\nexport interface HttpRequestData {\n requestId: string;\n method: string;\n path: string;\n body: string;\n headers?: any;\n}\n\nexport interface HttpLocalServerPlugin {\n /**\n * Inicia el servidor local en el dispositivo nativo.\n * Devuelve la IP y el puerto asignado.\n */\n connect(): Promise<HttpConnectResult>;\n\n /**\n * Detiene el servidor local.\n */\n disconnect(): Promise<void>;\n\n /**\n * Envía la respuesta de vuelta al cliente que hizo la petición.\n * El requestId debe coincidir con el recibido en 'onRequest'.\n */\n sendResponse(options: { requestId: string; body: string }): Promise<void>;\n\n /**\n * Escucha las peticiones HTTP entrantes.\n */\n addListener(\n eventName: 'onRequest',\n listenerFunc: (data: HttpRequestData) => void\n ): Promise<PluginListenerHandle>;\n\n /**\n * Elimina todos los listeners registrados.\n */\n removeAllListeners(): Promise<void>;\n}"]}
@@ -1,4 +1,10 @@
1
1
  import type { HttpLocalServerPlugin } from './definitions';
2
+ /**
3
+ * Registramos el plugin.
4
+ * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java
5
+ * y el @objc(HttpLocalServerPlugin) en Swift.
6
+ */
2
7
  declare const HttpLocalServer: HttpLocalServerPlugin;
3
8
  export * from './definitions';
4
9
  export { HttpLocalServer };
10
+ export default HttpLocalServer;
package/dist/esm/index.js CHANGED
@@ -1,7 +1,16 @@
1
1
  import { registerPlugin } from '@capacitor/core';
2
+ /**
3
+ * Registramos el plugin.
4
+ * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java
5
+ * y el @objc(HttpLocalServerPlugin) en Swift.
6
+ */
2
7
  const HttpLocalServer = registerPlugin('HttpLocalServer', {
3
- web: () => import('./web').then((m) => new m.HttpLocalServerWeb()),
8
+ web: () => import('./web').then(m => new m.HttpLocalServerWeb()),
4
9
  });
10
+ // Exportamos las interfaces para que el usuario pueda tipar sus variables
5
11
  export * from './definitions';
12
+ // Exportamos el objeto del plugin
6
13
  export { HttpLocalServer };
14
+ // Exportación por defecto opcional para mayor compatibilidad
15
+ export default HttpLocalServer;
7
16
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAIjD,MAAM,eAAe,GAAG,cAAc,CAAwB,iBAAiB,EAAE;IAC/E,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;CACnE,CAAC,CAAC;AAEH,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\n\nimport type { HttpLocalServerPlugin } from './definitions';\n\nconst HttpLocalServer = registerPlugin<HttpLocalServerPlugin>('HttpLocalServer', {\n web: () => import('./web').then((m) => new m.HttpLocalServerWeb()),\n});\n\nexport * from './definitions';\nexport { HttpLocalServer };\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjD;;;;GAIG;AACH,MAAM,eAAe,GAAG,cAAc,CAAwB,iBAAiB,EAAE;IAC/E,GAAG,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;CACjE,CAAC,CAAC;AAEH,0EAA0E;AAC1E,cAAc,eAAe,CAAC;AAE9B,kCAAkC;AAClC,OAAO,EAAE,eAAe,EAAE,CAAC;AAE3B,6DAA6D;AAC7D,eAAe,eAAe,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\nimport type { HttpLocalServerPlugin } from './definitions';\n\n/**\n * Registramos el plugin. \n * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java \n * y el @objc(HttpLocalServerPlugin) en Swift.\n */\nconst HttpLocalServer = registerPlugin<HttpLocalServerPlugin>('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\n\n// Exportamos las interfaces para que el usuario pueda tipar sus variables\nexport * from './definitions';\n\n// Exportamos el objeto del plugin\nexport { HttpLocalServer };\n\n// Exportación por defecto opcional para mayor compatibilidad\nexport default HttpLocalServer;"]}
package/dist/esm/web.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
- import type { HttpLocalServerPlugin } from './definitions';
2
+ import type { HttpLocalServerPlugin, HttpConnectResult } from './definitions';
3
3
  export declare class HttpLocalServerWeb extends WebPlugin implements HttpLocalServerPlugin {
4
- echo(options: {
5
- value: string;
6
- }): Promise<{
7
- value: string;
8
- }>;
4
+ connect(): Promise<HttpConnectResult>;
5
+ disconnect(): Promise<void>;
6
+ sendResponse(options: {
7
+ requestId: string;
8
+ body: string;
9
+ }): Promise<void>;
9
10
  }
package/dist/esm/web.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
2
  export class HttpLocalServerWeb extends WebPlugin {
3
- async echo(options) {
4
- console.log('ECHO', options);
5
- return options;
3
+ async connect() {
4
+ console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');
5
+ // Devolvemos un valor por defecto para no romper la ejecución en web
6
+ return { ip: '127.0.0.1', port: 8080 };
7
+ }
8
+ async disconnect() {
9
+ console.log('HttpLocalServer: Servidor detenido (Mock).');
10
+ }
11
+ async sendResponse(options) {
12
+ console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);
6
13
  }
7
14
  }
8
15
  //# sourceMappingURL=web.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAC/C,KAAK,CAAC,IAAI,CAAC,OAA0B;QACnC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC7B,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\n\nimport type { HttpLocalServerPlugin } from './definitions';\n\nexport class HttpLocalServerWeb extends WebPlugin implements HttpLocalServerPlugin {\n async echo(options: { value: string }): Promise<{ value: string }> {\n console.log('ECHO', options);\n return options;\n }\n}\n"]}
1
+ {"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAC/C,KAAK,CAAC,OAAO;QACX,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QACzF,qEAAqE;QACrE,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,UAAU;QACd,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAA4C;QAC7D,OAAO,CAAC,GAAG,CAAC,uDAAuD,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1F,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\nimport type { HttpLocalServerPlugin, HttpConnectResult } from './definitions';\n\nexport class HttpLocalServerWeb extends WebPlugin implements HttpLocalServerPlugin {\n async connect(): Promise<HttpConnectResult> {\n console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');\n // Devolvemos un valor por defecto para no romper la ejecución en web\n return { ip: '127.0.0.1', port: 8080 };\n }\n\n async disconnect(): Promise<void> {\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n }\n\n async sendResponse(options: { requestId: string; body: string }): Promise<void> {\n console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);\n }\n}"]}
@@ -1,15 +1,29 @@
1
1
  'use strict';
2
2
 
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
3
5
  var core = require('@capacitor/core');
4
6
 
7
+ /**
8
+ * Registramos el plugin.
9
+ * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java
10
+ * y el @objc(HttpLocalServerPlugin) en Swift.
11
+ */
5
12
  const HttpLocalServer = core.registerPlugin('HttpLocalServer', {
6
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.HttpLocalServerWeb()),
13
+ web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpLocalServerWeb()),
7
14
  });
8
15
 
9
16
  class HttpLocalServerWeb extends core.WebPlugin {
10
- async echo(options) {
11
- console.log('ECHO', options);
12
- return options;
17
+ async connect() {
18
+ console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');
19
+ // Devolvemos un valor por defecto para no romper la ejecución en web
20
+ return { ip: '127.0.0.1', port: 8080 };
21
+ }
22
+ async disconnect() {
23
+ console.log('HttpLocalServer: Servidor detenido (Mock).');
24
+ }
25
+ async sendResponse(options) {
26
+ console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);
13
27
  }
14
28
  }
15
29
 
@@ -19,4 +33,5 @@ var web = /*#__PURE__*/Object.freeze({
19
33
  });
20
34
 
21
35
  exports.HttpLocalServer = HttpLocalServer;
36
+ exports.default = HttpLocalServer;
22
37
  //# sourceMappingURL=plugin.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then((m) => new m.HttpLocalServerWeb()),\n});\nexport * from './definitions';\nexport { HttpLocalServer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class HttpLocalServerWeb extends WebPlugin {\n async echo(options) {\n console.log('ECHO', options);\n return options;\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AACK,MAAC,eAAe,GAAGA,mBAAc,CAAC,iBAAiB,EAAE;AAC1D,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;AACtE,CAAC;;ACFM,MAAM,kBAAkB,SAASC,cAAS,CAAC;AAClD,IAAI,MAAM,IAAI,CAAC,OAAO,EAAE;AACxB,QAAQ,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC;AACpC,QAAQ,OAAO,OAAO;AACtB,IAAI;AACJ;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n * Registramos el plugin.\n * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java\n * y el @objc(HttpLocalServerPlugin) en Swift.\n */\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\n// Exportamos las interfaces para que el usuario pueda tipar sus variables\nexport * from './definitions';\n// Exportamos el objeto del plugin\nexport { HttpLocalServer };\n// Exportación por defecto opcional para mayor compatibilidad\nexport default HttpLocalServer;\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class HttpLocalServerWeb extends WebPlugin {\n async connect() {\n console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');\n // Devolvemos un valor por defecto para no romper la ejecución en web\n return { ip: '127.0.0.1', port: 8080 };\n }\n async disconnect() {\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n }\n async sendResponse(options) {\n console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;;;AACA;AACA;AACA;AACA;AACA;AACK,MAAC,eAAe,GAAGA,mBAAc,CAAC,iBAAiB,EAAE;AAC1D,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;AACpE,CAAC;;ACPM,MAAM,kBAAkB,SAASC,cAAS,CAAC;AAClD,IAAI,MAAM,OAAO,GAAG;AACpB,QAAQ,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC;AAChG;AACA,QAAQ,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE;AAC9C,IAAI;AACJ,IAAI,MAAM,UAAU,GAAG;AACvB,QAAQ,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;AACjE,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,OAAO,EAAE;AAChC,QAAQ,OAAO,CAAC,GAAG,CAAC,uDAAuD,EAAE,OAAO,CAAC,SAAS,CAAC;AAC/F,IAAI;AACJ;;;;;;;;;;"}
package/dist/plugin.js CHANGED
@@ -1,14 +1,26 @@
1
1
  var capacitorHttpLocalServer = (function (exports, core) {
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * Registramos el plugin.
6
+ * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java
7
+ * y el @objc(HttpLocalServerPlugin) en Swift.
8
+ */
4
9
  const HttpLocalServer = core.registerPlugin('HttpLocalServer', {
5
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.HttpLocalServerWeb()),
10
+ web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpLocalServerWeb()),
6
11
  });
7
12
 
8
13
  class HttpLocalServerWeb extends core.WebPlugin {
9
- async echo(options) {
10
- console.log('ECHO', options);
11
- return options;
14
+ async connect() {
15
+ console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');
16
+ // Devolvemos un valor por defecto para no romper la ejecución en web
17
+ return { ip: '127.0.0.1', port: 8080 };
18
+ }
19
+ async disconnect() {
20
+ console.log('HttpLocalServer: Servidor detenido (Mock).');
21
+ }
22
+ async sendResponse(options) {
23
+ console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);
12
24
  }
13
25
  }
14
26
 
@@ -18,6 +30,9 @@ var capacitorHttpLocalServer = (function (exports, core) {
18
30
  });
19
31
 
20
32
  exports.HttpLocalServer = HttpLocalServer;
33
+ exports.default = HttpLocalServer;
34
+
35
+ Object.defineProperty(exports, '__esModule', { value: true });
21
36
 
22
37
  return exports;
23
38
 
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then((m) => new m.HttpLocalServerWeb()),\n});\nexport * from './definitions';\nexport { HttpLocalServer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class HttpLocalServerWeb extends WebPlugin {\n async echo(options) {\n console.log('ECHO', options);\n return options;\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;AACK,UAAC,eAAe,GAAGA,mBAAc,CAAC,iBAAiB,EAAE;IAC1D,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;IACtE,CAAC;;ICFM,MAAM,kBAAkB,SAASC,cAAS,CAAC;IAClD,IAAI,MAAM,IAAI,CAAC,OAAO,EAAE;IACxB,QAAQ,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC;IACpC,QAAQ,OAAO,OAAO;IACtB,IAAI;IACJ;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n * Registramos el plugin.\n * El nombre 'HttpLocalServer' debe coincidir con el @CapacitorPlugin en Java\n * y el @objc(HttpLocalServerPlugin) en Swift.\n */\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\n// Exportamos las interfaces para que el usuario pueda tipar sus variables\nexport * from './definitions';\n// Exportamos el objeto del plugin\nexport { HttpLocalServer };\n// Exportación por defecto opcional para mayor compatibilidad\nexport default HttpLocalServer;\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class HttpLocalServerWeb extends WebPlugin {\n async connect() {\n console.warn('HttpLocalServer: El servidor nativo no se puede iniciar en el navegador.');\n // Devolvemos un valor por defecto para no romper la ejecución en web\n return { ip: '127.0.0.1', port: 8080 };\n }\n async disconnect() {\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n }\n async sendResponse(options) {\n console.log('HttpLocalServer: Respuesta mock enviada al requestId:', options.requestId);\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IACA;IACA;IACA;IACA;IACA;AACK,UAAC,eAAe,GAAGA,mBAAc,CAAC,iBAAiB,EAAE;IAC1D,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;IACpE,CAAC;;ICPM,MAAM,kBAAkB,SAASC,cAAS,CAAC;IAClD,IAAI,MAAM,OAAO,GAAG;IACpB,QAAQ,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC;IAChG;IACA,QAAQ,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE;IAC9C,IAAI;IACJ,IAAI,MAAM,UAAU,GAAG;IACvB,QAAQ,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;IACjE,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,OAAO,EAAE;IAChC,QAAQ,OAAO,CAAC,GAAG,CAAC,uDAAuD,EAAE,OAAO,CAAC,SAAS,CAAC;IAC/F,IAAI;IACJ;;;;;;;;;;;;;;;;;;"}
@@ -29,33 +29,68 @@ public protocol HttpLocalServerDelegate: AnyObject {
29
29
  weak var delegate: HttpLocalServerDelegate?
30
30
  static var pendingResponses = [String: (String) -> Void]()
31
31
  static let queue = DispatchQueue(label: "HttpLocalServer.pendingResponses")
32
-
32
+
33
33
  public init(delegate: HttpLocalServerDelegate) {
34
34
  self.delegate = delegate
35
35
  }
36
-
36
+
37
37
  @objc public func connect(_ call: CAPPluginCall) {
38
38
  DispatchQueue.main.async { [weak self] in
39
39
  guard let self = self else { return }
40
+
40
41
  self.webServer = GCDWebServer()
41
-
42
- // Handlers específicos por método HTTP
43
- self.webServer?.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self) { request in
44
- return self.handleRequest(request: request, method: "GET")
45
- }
46
-
47
- self.webServer?.addDefaultHandler(forMethod: "POST", request: GCDWebServerDataRequest.self) { request in
48
- return self.handleRequest(request: request, method: "POST")
49
- }
50
-
51
- self.webServer?.addDefaultHandler(forMethod: "PUT", request: GCDWebServerDataRequest.self) { request in
52
- return self.handleRequest(request: request, method: "PUT")
53
- }
54
-
55
- self.webServer?.addDefaultHandler(forMethod: "DELETE", request: GCDWebServerRequest.self) { request in
56
- return self.handleRequest(request: request, method: "DELETE")
57
- }
58
-
42
+
43
+ self.webServer?.addHandler(
44
+ match: { method, url, headers, path, query in
45
+ GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query)
46
+ },
47
+ processBlock: { request in
48
+ let method = request.method
49
+ let path = request.url.path
50
+ var body: String? = nil
51
+
52
+ if let dataRequest = request as? GCDWebServerDataRequest, let text = String(data: dataRequest.data, encoding: .utf8) {
53
+ body = text
54
+ }
55
+
56
+ let requestId = UUID().uuidString
57
+ var responseString: String? = nil
58
+
59
+ // Set up a semaphore so we can block until JS responds or timeout (3s)
60
+ let semaphore = DispatchSemaphore(value: 0)
61
+ Self.queue.async {
62
+ Self.pendingResponses[requestId] = { responseBody in
63
+ responseString = responseBody
64
+ semaphore.signal()
65
+ }
66
+ }
67
+
68
+ // Notify delegate (plugin) with the request info
69
+ let req: [String: Any?] = [
70
+ "requestId": requestId,
71
+ "method": method,
72
+ "path": path,
73
+ "body": body
74
+ ]
75
+ self.delegate?.httpLocalServerDidReceiveRequest(req.compactMapValues { $0 })
76
+
77
+ // Wait for JS response or timeout
78
+ _ = semaphore.wait(timeout: .now() + 3.0)
79
+ Self.queue.async {
80
+ Self.pendingResponses.removeValue(forKey: requestId)
81
+ }
82
+ let reply = responseString ?? "{\"error\":\"Timeout waiting for JS response\"}"
83
+
84
+ let response = GCDWebServerDataResponse(text: reply)
85
+ response?.setValue("*", forAdditionalHeader: "Access-Control-Allow-Origin")
86
+ response?.setValue("GET,POST,OPTIONS", forAdditionalHeader: "Access-Control-Allow-Methods")
87
+ response?.setValue("origin, content-type, accept, authorization", forAdditionalHeader: "Access-Control-Allow-Headers")
88
+ response?.setValue("3600", forAdditionalHeader: "Access-Control-Max-Age")
89
+ response?.contentType = "application/json"
90
+ return response!
91
+ }
92
+ )
93
+
59
94
  let port: UInt = 8080
60
95
  do {
61
96
  try self.webServer?.start(options: [
@@ -73,58 +108,7 @@ public protocol HttpLocalServerDelegate: AnyObject {
73
108
  }
74
109
  }
75
110
  }
76
-
77
- // Método para manejar todas las requests
78
- private func handleRequest(request: GCDWebServerRequest, method: String) -> GCDWebServerResponse {
79
- let path = request.url.path
80
- var body: String? = nil
81
-
82
- // Leer body si es POST o PUT
83
- if let dataRequest = request as? GCDWebServerDataRequest {
84
- if let text = String(data: dataRequest.data, encoding: .utf8) {
85
- body = text
86
- print("Body received: \(text)")
87
- }
88
- }
89
-
90
- let requestId = UUID().uuidString
91
- var responseString: String? = nil
92
-
93
- // Set up a semaphore so we can block until JS responds or timeout
94
- let semaphore = DispatchSemaphore(value: 0)
95
- Self.queue.async {
96
- Self.pendingResponses[requestId] = { responseBody in
97
- responseString = responseBody
98
- semaphore.signal()
99
- }
100
- }
101
-
102
- // Notify delegate (plugin) with the request info
103
- let req: [String: Any?] = [
104
- "requestId": requestId,
105
- "method": method,
106
- "path": path,
107
- "body": body,
108
- "headers": request.headers
109
- ]
110
- self.delegate?.httpLocalServerDidReceiveRequest(req.compactMapValues { $0 })
111
-
112
- // Wait for JS response or timeout (55 segundos)
113
- _ = semaphore.wait(timeout: .now() + 55.0)
114
- Self.queue.async {
115
- Self.pendingResponses.removeValue(forKey: requestId)
116
- }
117
-
118
- let reply = responseString ?? "{\"error\":\"Timeout waiting for JS response\"}"
119
- let response = GCDWebServerDataResponse(text: reply)
120
- response?.setValue("*", forAdditionalHeader: "Access-Control-Allow-Origin")
121
- response?.setValue("GET,POST,OPTIONS,PUT,DELETE", forAdditionalHeader: "Access-Control-Allow-Methods")
122
- response?.setValue("origin, content-type, accept, authorization", forAdditionalHeader: "Access-Control-Allow-Headers")
123
- response?.setValue("3600", forAdditionalHeader: "Access-Control-Max-Age")
124
- response?.contentType = "application/json"
125
- return response!
126
- }
127
-
111
+
128
112
  @objc public func disconnect(_ call: CAPPluginCall) {
129
113
  DispatchQueue.main.async { [weak self] in
130
114
  self?.webServer?.stop()
@@ -132,7 +116,7 @@ public protocol HttpLocalServerDelegate: AnyObject {
132
116
  call.resolve()
133
117
  }
134
118
  }
135
-
119
+
136
120
  // Called by plugin when JS responds
137
121
  static func handleJsResponse(requestId: String, body: String) {
138
122
  queue.async {
@@ -142,7 +126,7 @@ public protocol HttpLocalServerDelegate: AnyObject {
142
126
  }
143
127
  }
144
128
  }
145
-
129
+
146
130
  // Helper: get WiFi IP address (IPv4)
147
131
  static func getWiFiAddress() -> String? {
148
132
  var address: String?
@@ -170,4 +154,4 @@ public protocol HttpLocalServerDelegate: AnyObject {
170
154
  }
171
155
  return address
172
156
  }
173
- }
157
+ }
@@ -0,0 +1,15 @@
1
+ import XCTest
2
+ @testable import HttpLocalServerPlugin
3
+
4
+ class HttpLocalServerTests: XCTestCase {
5
+ func testEcho() {
6
+ // This is an example of a functional test case for a plugin.
7
+ // Use XCTAssert and related functions to verify your tests produce the correct results.
8
+
9
+ let implementation = HttpLocalServer()
10
+ let value = "Hello, World!"
11
+ let result = implementation.echo(value)
12
+
13
+ XCTAssertEqual(value, result)
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cappitolian/http-local-server",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Runs a local HTTP server on your device, accessible over LAN. Supports connect, disconnect, GET, and POST methods with IP and port discovery.",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",
@@ -48,7 +48,7 @@
48
48
  "devDependencies": {
49
49
  "@capacitor/android": "^7.0.0",
50
50
  "@capacitor/core": "^7.0.0",
51
- "@capacitor/docgen": "^0.3.1",
51
+ "@capacitor/docgen": "^0.3.0",
52
52
  "@capacitor/ios": "^7.0.0",
53
53
  "@ionic/eslint-config": "^0.4.0",
54
54
  "@ionic/prettier-config": "^4.0.0",
@@ -59,10 +59,10 @@
59
59
  "rimraf": "^6.1.0",
60
60
  "rollup": "^4.53.2",
61
61
  "swiftlint": "^2.0.0",
62
- "typescript": "^5.9.3"
62
+ "typescript": "~5.4.0"
63
63
  },
64
64
  "peerDependencies": {
65
- "@capacitor/core": ">=7.0.0"
65
+ "@capacitor/core": "^7.0.0"
66
66
  },
67
67
  "prettier": "@ionic/prettier-config",
68
68
  "swiftlint": "@ionic/swiftlint-config",
@@ -77,4 +77,4 @@
77
77
  "src": "android"
78
78
  }
79
79
  }
80
- }
80
+ }