@cappitolian/http-local-server 0.0.8 → 0.0.9
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/android/src/main/java/com/cappitolian/plugins/httplocalserver/HttpLocalServer.java +306 -108
- package/android/src/main/java/com/cappitolian/plugins/httplocalserver/HttpLocalServerPlugin.java +47 -11
- package/dist/docs.json +115 -19
- package/dist/esm/definitions.d.ts +35 -6
- package/dist/esm/definitions.js.map +1 -1
- package/dist/esm/index.d.ts +24 -3
- package/dist/esm/index.js +24 -6
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/web.d.ts +7 -5
- package/dist/esm/web.js +36 -4
- package/dist/esm/web.js.map +1 -1
- package/dist/plugin.cjs.js +60 -7
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js +60 -7
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/HttpLocalServerPlugin/HttpLocalServer.swift +3 -1
- package/package.json +1 -1
|
@@ -25,167 +25,365 @@
|
|
|
25
25
|
package com.cappitolian.plugins.httplocalservice;
|
|
26
26
|
|
|
27
27
|
import android.content.Context;
|
|
28
|
+
import android.net.wifi.WifiInfo;
|
|
28
29
|
import android.net.wifi.WifiManager;
|
|
29
30
|
import android.text.format.Formatter;
|
|
31
|
+
import android.util.Log;
|
|
32
|
+
|
|
33
|
+
import androidx.annotation.NonNull;
|
|
34
|
+
import androidx.annotation.Nullable;
|
|
35
|
+
|
|
30
36
|
import com.getcapacitor.JSObject;
|
|
31
37
|
import com.getcapacitor.Plugin;
|
|
32
38
|
import com.getcapacitor.PluginCall;
|
|
33
|
-
|
|
39
|
+
|
|
40
|
+
import org.json.JSONException;
|
|
41
|
+
import org.json.JSONObject;
|
|
42
|
+
|
|
34
43
|
import java.io.IOException;
|
|
35
|
-
import java.util.UUID;
|
|
36
|
-
import java.util.concurrent.*;
|
|
37
44
|
import java.util.HashMap;
|
|
38
45
|
import java.util.Map;
|
|
46
|
+
import java.util.UUID;
|
|
47
|
+
import java.util.concurrent.CompletableFuture;
|
|
48
|
+
import java.util.concurrent.ConcurrentHashMap;
|
|
49
|
+
import java.util.concurrent.TimeUnit;
|
|
50
|
+
import java.util.concurrent.TimeoutException;
|
|
51
|
+
|
|
52
|
+
import fi.iki.elonen.NanoHTTPD;
|
|
39
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Local HTTP server implementation for Android using NanoHTTPD.
|
|
56
|
+
* Handles incoming HTTP requests and communicates with JavaScript layer.
|
|
57
|
+
*/
|
|
40
58
|
public class HttpLocalServer {
|
|
59
|
+
|
|
60
|
+
// MARK: - Constants
|
|
61
|
+
private static final String TAG = "HttpLocalServer";
|
|
62
|
+
private static final int DEFAULT_PORT = 8080;
|
|
63
|
+
private static final int DEFAULT_TIMEOUT_SECONDS = 5;
|
|
64
|
+
private static final String FALLBACK_IP = "127.0.0.1";
|
|
65
|
+
|
|
66
|
+
// MARK: - Properties
|
|
41
67
|
private LocalNanoServer server;
|
|
42
|
-
private
|
|
43
|
-
private int port
|
|
44
|
-
private
|
|
45
|
-
|
|
46
|
-
// Map to wait for responses from JS (key: requestId)
|
|
68
|
+
private final Plugin plugin;
|
|
69
|
+
private final int port;
|
|
70
|
+
private final int timeoutSeconds;
|
|
71
|
+
|
|
47
72
|
private static final ConcurrentHashMap<String, CompletableFuture<String>> pendingResponses = new ConcurrentHashMap<>();
|
|
48
|
-
|
|
49
|
-
|
|
73
|
+
|
|
74
|
+
// MARK: - Constructor
|
|
75
|
+
public HttpLocalServer(@NonNull Plugin plugin) {
|
|
76
|
+
this(plugin, DEFAULT_PORT, DEFAULT_TIMEOUT_SECONDS);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
public HttpLocalServer(@NonNull Plugin plugin, int port, int timeoutSeconds) {
|
|
50
80
|
this.plugin = plugin;
|
|
81
|
+
this.port = port;
|
|
82
|
+
this.timeoutSeconds = timeoutSeconds;
|
|
51
83
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
server = new LocalNanoServer(localIp, port, plugin);
|
|
57
|
-
try {
|
|
58
|
-
server.start();
|
|
59
|
-
JSObject ret = new JSObject();
|
|
60
|
-
ret.put("ip", localIp);
|
|
61
|
-
ret.put("port", port);
|
|
62
|
-
call.resolve(ret);
|
|
63
|
-
} catch (Exception e) {
|
|
64
|
-
call.reject("Failed to start server: " + e.getMessage());
|
|
65
|
-
}
|
|
66
|
-
} else {
|
|
84
|
+
|
|
85
|
+
// MARK: - Public Methods
|
|
86
|
+
public void connect(@NonNull PluginCall call) {
|
|
87
|
+
if (server != null && server.isAlive()) {
|
|
67
88
|
call.reject("Server is already running");
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
String localIp = getLocalIpAddress(plugin.getContext());
|
|
94
|
+
server = new LocalNanoServer(localIp, port, plugin, timeoutSeconds);
|
|
95
|
+
server.start();
|
|
96
|
+
|
|
97
|
+
JSObject response = new JSObject();
|
|
98
|
+
response.put("ip", localIp);
|
|
99
|
+
response.put("port", port);
|
|
100
|
+
call.resolve(response);
|
|
101
|
+
|
|
102
|
+
Log.i(TAG, "Server started at " + localIp + ":" + port);
|
|
103
|
+
} catch (IOException e) {
|
|
104
|
+
Log.e(TAG, "Failed to start server", e);
|
|
105
|
+
call.reject("Failed to start server: " + e.getMessage());
|
|
68
106
|
}
|
|
69
107
|
}
|
|
70
|
-
|
|
71
|
-
public void disconnect(PluginCall call) {
|
|
108
|
+
|
|
109
|
+
public void disconnect(@Nullable PluginCall call) {
|
|
72
110
|
if (server != null) {
|
|
73
111
|
server.stop();
|
|
74
112
|
server = null;
|
|
113
|
+
|
|
114
|
+
// Clear all pending responses
|
|
115
|
+
pendingResponses.clear();
|
|
116
|
+
|
|
117
|
+
Log.i(TAG, "Server stopped");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (call != null) {
|
|
121
|
+
call.resolve();
|
|
75
122
|
}
|
|
76
|
-
call.resolve();
|
|
77
123
|
}
|
|
78
|
-
|
|
79
|
-
//
|
|
80
|
-
|
|
124
|
+
|
|
125
|
+
// MARK: - Static Methods
|
|
126
|
+
/**
|
|
127
|
+
* Called by plugin when JavaScript responds to a request
|
|
128
|
+
*/
|
|
129
|
+
public static void handleJsResponse(@NonNull String requestId, @NonNull String body) {
|
|
81
130
|
CompletableFuture<String> future = pendingResponses.remove(requestId);
|
|
82
|
-
if (future != null) {
|
|
131
|
+
if (future != null && !future.isDone()) {
|
|
83
132
|
future.complete(body);
|
|
133
|
+
Log.d(TAG, "Response received for request: " + requestId);
|
|
134
|
+
} else {
|
|
135
|
+
Log.w(TAG, "No pending request found for ID: " + requestId);
|
|
84
136
|
}
|
|
85
137
|
}
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
138
|
+
|
|
139
|
+
// MARK: - Private Methods
|
|
140
|
+
/**
|
|
141
|
+
* Get the local WiFi IP address
|
|
142
|
+
*/
|
|
143
|
+
@NonNull
|
|
144
|
+
private String getLocalIpAddress(@NonNull Context context) {
|
|
145
|
+
try {
|
|
146
|
+
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
|
|
147
|
+
.getSystemService(Context.WIFI_SERVICE);
|
|
148
|
+
|
|
149
|
+
if (wifiManager == null) {
|
|
150
|
+
Log.w(TAG, "WifiManager is null, using fallback IP");
|
|
151
|
+
return FALLBACK_IP;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
|
|
155
|
+
if (wifiInfo == null) {
|
|
156
|
+
Log.w(TAG, "WifiInfo is null, using fallback IP");
|
|
157
|
+
return FALLBACK_IP;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
int ipAddress = wifiInfo.getIpAddress();
|
|
161
|
+
if (ipAddress == 0) {
|
|
162
|
+
Log.w(TAG, "IP address is 0, using fallback IP");
|
|
163
|
+
return FALLBACK_IP;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return Formatter.formatIpAddress(ipAddress);
|
|
167
|
+
} catch (Exception e) {
|
|
168
|
+
Log.e(TAG, "Error getting IP address", e);
|
|
169
|
+
return FALLBACK_IP;
|
|
92
170
|
}
|
|
93
|
-
return "127.0.0.1"; // fallback
|
|
94
171
|
}
|
|
95
|
-
|
|
172
|
+
|
|
173
|
+
// MARK: - Inner Class: LocalNanoServer
|
|
174
|
+
/**
|
|
175
|
+
* NanoHTTPD server implementation that handles HTTP requests
|
|
176
|
+
*/
|
|
96
177
|
private static class LocalNanoServer extends NanoHTTPD {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
178
|
+
|
|
179
|
+
private final Plugin plugin;
|
|
180
|
+
private final int timeoutSeconds;
|
|
181
|
+
|
|
182
|
+
public LocalNanoServer(@NonNull String hostname, int port, @NonNull Plugin plugin, int timeoutSeconds) {
|
|
100
183
|
super(hostname, port);
|
|
101
184
|
this.plugin = plugin;
|
|
185
|
+
this.timeoutSeconds = timeoutSeconds;
|
|
102
186
|
}
|
|
103
|
-
|
|
187
|
+
|
|
104
188
|
@Override
|
|
105
|
-
public Response serve(IHTTPSession session) {
|
|
106
|
-
String path = session.getUri();
|
|
189
|
+
public Response serve(@NonNull IHTTPSession session) {
|
|
107
190
|
String method = session.getMethod().name();
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
191
|
+
String path = session.getUri();
|
|
192
|
+
|
|
193
|
+
// Handle CORS preflight
|
|
194
|
+
if (Method.OPTIONS.equals(session.getMethod())) {
|
|
195
|
+
return createCorsResponse();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
try {
|
|
199
|
+
// Extract request data
|
|
200
|
+
String body = extractBody(session);
|
|
201
|
+
Map<String, String> headers = session.getHeaders();
|
|
202
|
+
Map<String, String> params = session.getParms();
|
|
203
|
+
|
|
204
|
+
// Process request
|
|
205
|
+
String responseBody = processRequest(method, path, body, headers, params);
|
|
206
|
+
|
|
207
|
+
return createJsonResponse(responseBody, Response.Status.OK);
|
|
208
|
+
} catch (Exception e) {
|
|
209
|
+
Log.e(TAG, "Error processing request", e);
|
|
210
|
+
return createErrorResponse("Internal server error: " + e.getMessage(),
|
|
211
|
+
Response.Status.INTERNAL_ERROR);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Extract body from POST/PUT/PATCH requests
|
|
217
|
+
*/
|
|
218
|
+
@Nullable
|
|
219
|
+
private String extractBody(@NonNull IHTTPSession session) {
|
|
220
|
+
Method method = session.getMethod();
|
|
221
|
+
|
|
222
|
+
if (method != Method.POST && method != Method.PUT && method != Method.PATCH) {
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
HashMap<String, String> files = new HashMap<>();
|
|
228
|
+
session.parseBody(files);
|
|
229
|
+
|
|
230
|
+
// Body comes in the map with key "postData"
|
|
231
|
+
String body = files.get("postData");
|
|
232
|
+
|
|
233
|
+
// Fallback to query parameters for form-data
|
|
234
|
+
if (body == null || body.isEmpty()) {
|
|
235
|
+
body = session.getQueryParameterString();
|
|
132
236
|
}
|
|
237
|
+
|
|
238
|
+
Log.d(TAG, "Body received (" + body.length() + " bytes): " +
|
|
239
|
+
(body != null ? body.substring(0, Math.min(body.length(), 100)) : "null"));
|
|
240
|
+
|
|
241
|
+
return body;
|
|
242
|
+
} catch (IOException | ResponseException e) {
|
|
243
|
+
Log.e(TAG, "Error parsing body", e);
|
|
244
|
+
return null;
|
|
133
245
|
}
|
|
134
|
-
|
|
135
|
-
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Process the request and wait for JavaScript response
|
|
250
|
+
*/
|
|
251
|
+
@NonNull
|
|
252
|
+
private String processRequest(@NonNull String method, @NonNull String path,
|
|
253
|
+
@Nullable String body, @NonNull Map<String, String> headers,
|
|
254
|
+
@NonNull Map<String, String> params) {
|
|
255
|
+
|
|
136
256
|
String requestId = UUID.randomUUID().toString();
|
|
137
|
-
|
|
138
|
-
//
|
|
139
|
-
JSObject
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
257
|
+
|
|
258
|
+
// Build request data for JavaScript
|
|
259
|
+
JSObject requestData = new JSObject();
|
|
260
|
+
requestData.put("requestId", requestId);
|
|
261
|
+
requestData.put("method", method);
|
|
262
|
+
requestData.put("path", path);
|
|
263
|
+
|
|
264
|
+
if (body != null && !body.isEmpty()) {
|
|
265
|
+
requestData.put("body", body);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!headers.isEmpty()) {
|
|
269
|
+
requestData.put("headers", mapToJson(headers));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (!params.isEmpty()) {
|
|
273
|
+
requestData.put("query", mapToJson(params));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Create future for response
|
|
147
277
|
CompletableFuture<String> future = new CompletableFuture<>();
|
|
148
278
|
pendingResponses.put(requestId, future);
|
|
149
|
-
|
|
150
|
-
//
|
|
151
|
-
if (plugin instanceof
|
|
152
|
-
((
|
|
279
|
+
|
|
280
|
+
// Notify plugin
|
|
281
|
+
if (plugin instanceof HttpLocalServerPlugin) {
|
|
282
|
+
((HttpLocalServerPlugin) plugin).fireOnRequest(requestData);
|
|
283
|
+
} else {
|
|
284
|
+
Log.e(TAG, "Plugin is not instance of HttpLocalServerPlugin");
|
|
153
285
|
}
|
|
154
|
-
|
|
155
|
-
|
|
286
|
+
|
|
287
|
+
// Wait for JavaScript response
|
|
156
288
|
try {
|
|
157
|
-
|
|
158
|
-
|
|
289
|
+
String response = future.get(timeoutSeconds, TimeUnit.SECONDS);
|
|
290
|
+
Log.d(TAG, "Response received for request: " + requestId);
|
|
291
|
+
return response;
|
|
159
292
|
} catch (TimeoutException e) {
|
|
160
|
-
|
|
293
|
+
Log.w(TAG, "Timeout waiting for response: " + requestId);
|
|
294
|
+
return createTimeoutError(requestId);
|
|
161
295
|
} catch (Exception e) {
|
|
162
|
-
|
|
296
|
+
Log.e(TAG, "Error waiting for response: " + requestId, e);
|
|
297
|
+
return createGenericError("Error waiting for response");
|
|
163
298
|
} finally {
|
|
164
299
|
pendingResponses.remove(requestId);
|
|
165
300
|
}
|
|
166
|
-
|
|
167
|
-
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Convert Map to JSObject
|
|
305
|
+
*/
|
|
306
|
+
@NonNull
|
|
307
|
+
private JSObject mapToJson(@NonNull Map<String, String> map) {
|
|
308
|
+
JSObject json = new JSObject();
|
|
309
|
+
for (Map.Entry<String, String> entry : map.entrySet()) {
|
|
310
|
+
json.put(entry.getKey(), entry.getValue());
|
|
311
|
+
}
|
|
312
|
+
return json;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Create JSON response with CORS headers
|
|
317
|
+
*/
|
|
318
|
+
@NonNull
|
|
319
|
+
private Response createJsonResponse(@NonNull String body, @NonNull Response.Status status) {
|
|
320
|
+
Response response = newFixedLengthResponse(status, "application/json", body);
|
|
168
321
|
addCorsHeaders(response);
|
|
169
322
|
return response;
|
|
170
323
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Create CORS preflight response
|
|
327
|
+
*/
|
|
328
|
+
@NonNull
|
|
329
|
+
private Response createCorsResponse() {
|
|
330
|
+
Response response = newFixedLengthResponse(Response.Status.NO_CONTENT,
|
|
331
|
+
"text/plain", "");
|
|
332
|
+
addCorsHeaders(response);
|
|
333
|
+
return response;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Create error response
|
|
338
|
+
*/
|
|
339
|
+
@NonNull
|
|
340
|
+
private Response createErrorResponse(@NonNull String message, @NonNull Response.Status status) {
|
|
175
341
|
try {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
} catch (
|
|
180
|
-
|
|
342
|
+
JSONObject error = new JSONObject();
|
|
343
|
+
error.put("error", message);
|
|
344
|
+
return createJsonResponse(error.toString(), status);
|
|
345
|
+
} catch (JSONException e) {
|
|
346
|
+
return newFixedLengthResponse(status, "text/plain", message);
|
|
181
347
|
}
|
|
182
|
-
return headers;
|
|
183
348
|
}
|
|
184
|
-
|
|
185
|
-
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Create timeout error JSON
|
|
352
|
+
*/
|
|
353
|
+
@NonNull
|
|
354
|
+
private String createTimeoutError(@NonNull String requestId) {
|
|
355
|
+
try {
|
|
356
|
+
JSONObject error = new JSONObject();
|
|
357
|
+
error.put("error", "Request timeout");
|
|
358
|
+
error.put("requestId", requestId);
|
|
359
|
+
return error.toString();
|
|
360
|
+
} catch (JSONException e) {
|
|
361
|
+
return "{\"error\":\"Request timeout\"}";
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Create generic error JSON
|
|
367
|
+
*/
|
|
368
|
+
@NonNull
|
|
369
|
+
private String createGenericError(@NonNull String message) {
|
|
370
|
+
try {
|
|
371
|
+
JSONObject error = new JSONObject();
|
|
372
|
+
error.put("error", message);
|
|
373
|
+
return error.toString();
|
|
374
|
+
} catch (JSONException e) {
|
|
375
|
+
return "{\"error\":\"" + message + "\"}";
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Add CORS headers to response
|
|
381
|
+
*/
|
|
382
|
+
private void addCorsHeaders(@NonNull Response response) {
|
|
186
383
|
response.addHeader("Access-Control-Allow-Origin", "*");
|
|
187
|
-
response.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
|
|
188
|
-
response.addHeader("Access-Control-Allow-Headers", "
|
|
384
|
+
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
|
|
385
|
+
response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
|
|
386
|
+
response.addHeader("Access-Control-Allow-Credentials", "true");
|
|
189
387
|
response.addHeader("Access-Control-Max-Age", "3600");
|
|
190
388
|
}
|
|
191
389
|
}
|
package/android/src/main/java/com/cappitolian/plugins/httplocalserver/HttpLocalServerPlugin.java
CHANGED
|
@@ -46,16 +46,34 @@
|
|
|
46
46
|
|
|
47
47
|
package com.cappitolian.plugins.httplocalservice;
|
|
48
48
|
|
|
49
|
-
import
|
|
49
|
+
import android.util.Log;
|
|
50
|
+
|
|
51
|
+
import androidx.annotation.NonNull;
|
|
52
|
+
|
|
53
|
+
import com.getcapacitor.JSObject;
|
|
54
|
+
import com.getcapacitor.Plugin;
|
|
55
|
+
import com.getcapacitor.PluginCall;
|
|
56
|
+
import com.getcapacitor.PluginMethod;
|
|
50
57
|
import com.getcapacitor.annotation.CapacitorPlugin;
|
|
51
|
-
import org.json.JSONException;
|
|
52
|
-
import org.json.JSONObject;
|
|
53
58
|
|
|
54
59
|
@CapacitorPlugin(name = "HttpLocalServer")
|
|
55
60
|
public class HttpLocalServerPlugin extends Plugin {
|
|
56
|
-
|
|
61
|
+
|
|
62
|
+
private static final String TAG = "HttpLocalServerPlugin";
|
|
57
63
|
private HttpLocalServer localServer;
|
|
58
64
|
|
|
65
|
+
@Override
|
|
66
|
+
public void load() {
|
|
67
|
+
super.load();
|
|
68
|
+
// Inicializar el servidor con configuración por defecto
|
|
69
|
+
localServer = new HttpLocalServer(this);
|
|
70
|
+
|
|
71
|
+
// O con configuración personalizada:
|
|
72
|
+
// localServer = new HttpLocalServer(this, 8080, 5); // puerto y timeout
|
|
73
|
+
|
|
74
|
+
Log.d(TAG, "Plugin loaded");
|
|
75
|
+
}
|
|
76
|
+
|
|
59
77
|
@PluginMethod
|
|
60
78
|
public void connect(PluginCall call) {
|
|
61
79
|
if (localServer == null) {
|
|
@@ -64,11 +82,6 @@ public class HttpLocalServerPlugin extends Plugin {
|
|
|
64
82
|
localServer.connect(call);
|
|
65
83
|
}
|
|
66
84
|
|
|
67
|
-
// Add this method:
|
|
68
|
-
public void fireOnRequest(JSObject req) {
|
|
69
|
-
notifyListeners("onRequest", req, true);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
85
|
@PluginMethod
|
|
73
86
|
public void disconnect(PluginCall call) {
|
|
74
87
|
if (localServer != null) {
|
|
@@ -82,11 +95,34 @@ public class HttpLocalServerPlugin extends Plugin {
|
|
|
82
95
|
public void sendResponse(PluginCall call) {
|
|
83
96
|
String requestId = call.getString("requestId");
|
|
84
97
|
String body = call.getString("body");
|
|
85
|
-
|
|
86
|
-
|
|
98
|
+
|
|
99
|
+
if (requestId == null || requestId.isEmpty()) {
|
|
100
|
+
call.reject("Missing requestId");
|
|
87
101
|
return;
|
|
88
102
|
}
|
|
103
|
+
|
|
104
|
+
if (body == null || body.isEmpty()) {
|
|
105
|
+
call.reject("Missing body");
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
89
109
|
HttpLocalServer.handleJsResponse(requestId, body);
|
|
90
110
|
call.resolve();
|
|
91
111
|
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Called by HttpLocalServer to notify JavaScript of incoming requests
|
|
115
|
+
*/
|
|
116
|
+
public void fireOnRequest(@NonNull JSObject data) {
|
|
117
|
+
notifyListeners("onRequest", data);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
@Override
|
|
121
|
+
protected void handleOnDestroy() {
|
|
122
|
+
if (localServer != null) {
|
|
123
|
+
localServer.disconnect(null);
|
|
124
|
+
localServer = null;
|
|
125
|
+
}
|
|
126
|
+
super.handleOnDestroy();
|
|
127
|
+
}
|
|
92
128
|
}
|
package/dist/docs.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"api": {
|
|
3
3
|
"name": "HttpLocalServerPlugin",
|
|
4
4
|
"slug": "httplocalserverplugin",
|
|
5
|
-
"docs": "",
|
|
5
|
+
"docs": "Plugin para manejar un servidor HTTP local en dispositivos nativos",
|
|
6
6
|
"tags": [],
|
|
7
7
|
"methods": [
|
|
8
8
|
{
|
|
@@ -10,7 +10,16 @@
|
|
|
10
10
|
"signature": "() => Promise<HttpConnectResult>",
|
|
11
11
|
"parameters": [],
|
|
12
12
|
"returns": "Promise<HttpConnectResult>",
|
|
13
|
-
"tags": [
|
|
13
|
+
"tags": [
|
|
14
|
+
{
|
|
15
|
+
"name": "returns",
|
|
16
|
+
"text": "Promesa con la IP y puerto del servidor"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"name": "throws",
|
|
20
|
+
"text": "Error si el servidor no puede iniciarse"
|
|
21
|
+
}
|
|
22
|
+
],
|
|
14
23
|
"docs": "Inicia el servidor local en el dispositivo nativo.\nDevuelve la IP y el puerto asignado.",
|
|
15
24
|
"complexTypes": [
|
|
16
25
|
"HttpConnectResult"
|
|
@@ -22,25 +31,45 @@
|
|
|
22
31
|
"signature": "() => Promise<void>",
|
|
23
32
|
"parameters": [],
|
|
24
33
|
"returns": "Promise<void>",
|
|
25
|
-
"tags": [
|
|
26
|
-
|
|
34
|
+
"tags": [
|
|
35
|
+
{
|
|
36
|
+
"name": "returns",
|
|
37
|
+
"text": "Promesa que se resuelve cuando el servidor se detiene"
|
|
38
|
+
}
|
|
39
|
+
],
|
|
40
|
+
"docs": "Detiene el servidor local y limpia todos los recursos.",
|
|
27
41
|
"complexTypes": [],
|
|
28
42
|
"slug": "disconnect"
|
|
29
43
|
},
|
|
30
44
|
{
|
|
31
45
|
"name": "sendResponse",
|
|
32
|
-
"signature": "(options:
|
|
46
|
+
"signature": "(options: HttpSendResponseOptions) => Promise<void>",
|
|
33
47
|
"parameters": [
|
|
34
48
|
{
|
|
35
49
|
"name": "options",
|
|
36
|
-
"docs": "",
|
|
37
|
-
"type": "
|
|
50
|
+
"docs": "- Objeto con requestId y body de la respuesta",
|
|
51
|
+
"type": "HttpSendResponseOptions"
|
|
38
52
|
}
|
|
39
53
|
],
|
|
40
54
|
"returns": "Promise<void>",
|
|
41
|
-
"tags": [
|
|
55
|
+
"tags": [
|
|
56
|
+
{
|
|
57
|
+
"name": "param",
|
|
58
|
+
"text": "options - Objeto con requestId y body de la respuesta"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"name": "returns",
|
|
62
|
+
"text": "Promesa que se resuelve cuando la respuesta se envía"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"name": "throws",
|
|
66
|
+
"text": "Error si faltan requestId o body"
|
|
67
|
+
}
|
|
68
|
+
],
|
|
42
69
|
"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": [
|
|
70
|
+
"complexTypes": [
|
|
71
|
+
"HttpSendResponseOptions"
|
|
72
|
+
],
|
|
44
73
|
"slug": "sendresponse"
|
|
45
74
|
},
|
|
46
75
|
{
|
|
@@ -49,17 +78,30 @@
|
|
|
49
78
|
"parameters": [
|
|
50
79
|
{
|
|
51
80
|
"name": "eventName",
|
|
52
|
-
"docs": "",
|
|
81
|
+
"docs": "- Debe ser 'onRequest'",
|
|
53
82
|
"type": "'onRequest'"
|
|
54
83
|
},
|
|
55
84
|
{
|
|
56
85
|
"name": "listenerFunc",
|
|
57
|
-
"docs": "",
|
|
86
|
+
"docs": "- Callback que recibe los datos de la petición",
|
|
58
87
|
"type": "(data: HttpRequestData) => void"
|
|
59
88
|
}
|
|
60
89
|
],
|
|
61
90
|
"returns": "Promise<PluginListenerHandle>",
|
|
62
|
-
"tags": [
|
|
91
|
+
"tags": [
|
|
92
|
+
{
|
|
93
|
+
"name": "param",
|
|
94
|
+
"text": "eventName - Debe ser 'onRequest'"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"name": "param",
|
|
98
|
+
"text": "listenerFunc - Callback que recibe los datos de la petición"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"name": "returns",
|
|
102
|
+
"text": "Handle para remover el listener"
|
|
103
|
+
}
|
|
104
|
+
],
|
|
63
105
|
"docs": "Escucha las peticiones HTTP entrantes.",
|
|
64
106
|
"complexTypes": [
|
|
65
107
|
"PluginListenerHandle",
|
|
@@ -72,7 +114,12 @@
|
|
|
72
114
|
"signature": "() => Promise<void>",
|
|
73
115
|
"parameters": [],
|
|
74
116
|
"returns": "Promise<void>",
|
|
75
|
-
"tags": [
|
|
117
|
+
"tags": [
|
|
118
|
+
{
|
|
119
|
+
"name": "returns",
|
|
120
|
+
"text": "Promesa que se resuelve cuando se eliminan los listeners"
|
|
121
|
+
}
|
|
122
|
+
],
|
|
76
123
|
"docs": "Elimina todos los listeners registrados.",
|
|
77
124
|
"complexTypes": [],
|
|
78
125
|
"slug": "removealllisteners"
|
|
@@ -84,7 +131,7 @@
|
|
|
84
131
|
{
|
|
85
132
|
"name": "HttpConnectResult",
|
|
86
133
|
"slug": "httpconnectresult",
|
|
87
|
-
"docs": "",
|
|
134
|
+
"docs": "Resultado de la conexión del servidor",
|
|
88
135
|
"tags": [],
|
|
89
136
|
"methods": [],
|
|
90
137
|
"properties": [
|
|
@@ -104,6 +151,29 @@
|
|
|
104
151
|
}
|
|
105
152
|
]
|
|
106
153
|
},
|
|
154
|
+
{
|
|
155
|
+
"name": "HttpSendResponseOptions",
|
|
156
|
+
"slug": "httpsendresponseoptions",
|
|
157
|
+
"docs": "Opciones para enviar una respuesta",
|
|
158
|
+
"tags": [],
|
|
159
|
+
"methods": [],
|
|
160
|
+
"properties": [
|
|
161
|
+
{
|
|
162
|
+
"name": "requestId",
|
|
163
|
+
"tags": [],
|
|
164
|
+
"docs": "",
|
|
165
|
+
"complexTypes": [],
|
|
166
|
+
"type": "string"
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
"name": "body",
|
|
170
|
+
"tags": [],
|
|
171
|
+
"docs": "",
|
|
172
|
+
"complexTypes": [],
|
|
173
|
+
"type": "string"
|
|
174
|
+
}
|
|
175
|
+
]
|
|
176
|
+
},
|
|
107
177
|
{
|
|
108
178
|
"name": "PluginListenerHandle",
|
|
109
179
|
"slug": "pluginlistenerhandle",
|
|
@@ -123,7 +193,7 @@
|
|
|
123
193
|
{
|
|
124
194
|
"name": "HttpRequestData",
|
|
125
195
|
"slug": "httprequestdata",
|
|
126
|
-
"docs": "",
|
|
196
|
+
"docs": "Datos de una petición HTTP entrante",
|
|
127
197
|
"tags": [],
|
|
128
198
|
"methods": [],
|
|
129
199
|
"properties": [
|
|
@@ -153,19 +223,45 @@
|
|
|
153
223
|
"tags": [],
|
|
154
224
|
"docs": "",
|
|
155
225
|
"complexTypes": [],
|
|
156
|
-
"type": "string"
|
|
226
|
+
"type": "string | undefined"
|
|
157
227
|
},
|
|
158
228
|
{
|
|
159
229
|
"name": "headers",
|
|
160
230
|
"tags": [],
|
|
161
231
|
"docs": "",
|
|
162
|
-
"complexTypes": [
|
|
163
|
-
|
|
232
|
+
"complexTypes": [
|
|
233
|
+
"Record"
|
|
234
|
+
],
|
|
235
|
+
"type": "Record<string, string>"
|
|
236
|
+
},
|
|
237
|
+
{
|
|
238
|
+
"name": "query",
|
|
239
|
+
"tags": [],
|
|
240
|
+
"docs": "",
|
|
241
|
+
"complexTypes": [
|
|
242
|
+
"Record"
|
|
243
|
+
],
|
|
244
|
+
"type": "Record<string, string>"
|
|
164
245
|
}
|
|
165
246
|
]
|
|
166
247
|
}
|
|
167
248
|
],
|
|
168
249
|
"enums": [],
|
|
169
|
-
"typeAliases": [
|
|
250
|
+
"typeAliases": [
|
|
251
|
+
{
|
|
252
|
+
"name": "Record",
|
|
253
|
+
"slug": "record",
|
|
254
|
+
"docs": "Construct a type with a set of properties K of type T",
|
|
255
|
+
"types": [
|
|
256
|
+
{
|
|
257
|
+
"text": "{\r\n [P in K]: T;\r\n}",
|
|
258
|
+
"complexTypes": [
|
|
259
|
+
"K",
|
|
260
|
+
"T"
|
|
261
|
+
]
|
|
262
|
+
}
|
|
263
|
+
]
|
|
264
|
+
}
|
|
265
|
+
],
|
|
170
266
|
"pluginConfigs": []
|
|
171
267
|
}
|
|
@@ -1,39 +1,68 @@
|
|
|
1
1
|
import type { PluginListenerHandle } from '@capacitor/core';
|
|
2
|
+
/**
|
|
3
|
+
* Resultado de la conexión del servidor
|
|
4
|
+
*/
|
|
2
5
|
export interface HttpConnectResult {
|
|
3
6
|
ip: string;
|
|
4
7
|
port: number;
|
|
5
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Datos de una petición HTTP entrante
|
|
11
|
+
*/
|
|
6
12
|
export interface HttpRequestData {
|
|
7
13
|
requestId: string;
|
|
8
14
|
method: string;
|
|
9
15
|
path: string;
|
|
16
|
+
body?: string;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
query?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Opciones para enviar una respuesta
|
|
22
|
+
*/
|
|
23
|
+
export interface HttpSendResponseOptions {
|
|
24
|
+
requestId: string;
|
|
10
25
|
body: string;
|
|
11
|
-
headers?: any;
|
|
12
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Plugin para manejar un servidor HTTP local en dispositivos nativos
|
|
29
|
+
*/
|
|
13
30
|
export interface HttpLocalServerPlugin {
|
|
14
31
|
/**
|
|
15
32
|
* Inicia el servidor local en el dispositivo nativo.
|
|
16
33
|
* Devuelve la IP y el puerto asignado.
|
|
34
|
+
*
|
|
35
|
+
* @returns Promesa con la IP y puerto del servidor
|
|
36
|
+
* @throws Error si el servidor no puede iniciarse
|
|
17
37
|
*/
|
|
18
38
|
connect(): Promise<HttpConnectResult>;
|
|
19
39
|
/**
|
|
20
|
-
* Detiene el servidor local.
|
|
40
|
+
* Detiene el servidor local y limpia todos los recursos.
|
|
41
|
+
*
|
|
42
|
+
* @returns Promesa que se resuelve cuando el servidor se detiene
|
|
21
43
|
*/
|
|
22
44
|
disconnect(): Promise<void>;
|
|
23
45
|
/**
|
|
24
46
|
* Envía la respuesta de vuelta al cliente que hizo la petición.
|
|
25
47
|
* El requestId debe coincidir con el recibido en 'onRequest'.
|
|
48
|
+
*
|
|
49
|
+
* @param options - Objeto con requestId y body de la respuesta
|
|
50
|
+
* @returns Promesa que se resuelve cuando la respuesta se envía
|
|
51
|
+
* @throws Error si faltan requestId o body
|
|
26
52
|
*/
|
|
27
|
-
sendResponse(options:
|
|
28
|
-
requestId: string;
|
|
29
|
-
body: string;
|
|
30
|
-
}): Promise<void>;
|
|
53
|
+
sendResponse(options: HttpSendResponseOptions): Promise<void>;
|
|
31
54
|
/**
|
|
32
55
|
* Escucha las peticiones HTTP entrantes.
|
|
56
|
+
*
|
|
57
|
+
* @param eventName - Debe ser 'onRequest'
|
|
58
|
+
* @param listenerFunc - Callback que recibe los datos de la petición
|
|
59
|
+
* @returns Handle para remover el listener
|
|
33
60
|
*/
|
|
34
61
|
addListener(eventName: 'onRequest', listenerFunc: (data: HttpRequestData) => void): Promise<PluginListenerHandle>;
|
|
35
62
|
/**
|
|
36
63
|
* Elimina todos los listeners registrados.
|
|
64
|
+
*
|
|
65
|
+
* @returns Promesa que se resuelve cuando se eliminan los listeners
|
|
37
66
|
*/
|
|
38
67
|
removeAllListeners(): Promise<void>;
|
|
39
68
|
}
|
|
@@ -1 +1 @@
|
|
|
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
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\n/**\n * Resultado de la conexión del servidor\n */\nexport interface HttpConnectResult {\n ip: string;\n port: number;\n}\n\n/**\n * Datos de una petición HTTP entrante\n */\nexport interface HttpRequestData {\n requestId: string;\n method: string;\n path: string;\n body?: string; // Ahora es opcional (GET/DELETE no tienen body)\n headers?: Record<string, string>; // Mejor tipado que 'any'\n query?: Record<string, string>; // Agregado: query parameters\n}\n\n/**\n * Opciones para enviar una respuesta\n */\nexport interface HttpSendResponseOptions {\n requestId: string;\n body: string;\n}\n\n/**\n * Plugin para manejar un servidor HTTP local en dispositivos nativos\n */\nexport interface HttpLocalServerPlugin {\n /**\n * Inicia el servidor local en el dispositivo nativo.\n * Devuelve la IP y el puerto asignado.\n * \n * @returns Promesa con la IP y puerto del servidor\n * @throws Error si el servidor no puede iniciarse\n */\n connect(): Promise<HttpConnectResult>;\n\n /**\n * Detiene el servidor local y limpia todos los recursos.\n * \n * @returns Promesa que se resuelve cuando el servidor se detiene\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 * @param options - Objeto con requestId y body de la respuesta\n * @returns Promesa que se resuelve cuando la respuesta se envía\n * @throws Error si faltan requestId o body\n */\n sendResponse(options: HttpSendResponseOptions): Promise<void>;\n\n /**\n * Escucha las peticiones HTTP entrantes.\n * \n * @param eventName - Debe ser 'onRequest'\n * @param listenerFunc - Callback que recibe los datos de la petición\n * @returns Handle para remover el listener\n */\n addListener(\n eventName: 'onRequest',\n listenerFunc: (data: HttpRequestData) => void\n ): Promise<PluginListenerHandle>;\n\n /**\n * Elimina todos los listeners registrados.\n * \n * @returns Promesa que se resuelve cuando se eliminan los listeners\n */\n removeAllListeners(): Promise<void>;\n}"]}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,8 +1,29 @@
|
|
|
1
1
|
import type { HttpLocalServerPlugin } from './definitions';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Plugin de servidor HTTP local para Android e iOS.
|
|
4
|
+
*
|
|
5
|
+
* Permite crear un servidor HTTP en el dispositivo que puede recibir
|
|
6
|
+
* peticiones desde otros dispositivos en la misma red.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { HttpLocalServer } from '@cappitolian/http-local-server';
|
|
11
|
+
*
|
|
12
|
+
* // Iniciar servidor
|
|
13
|
+
* const { ip, port } = await HttpLocalServer.connect();
|
|
14
|
+
* console.log(`Servidor en http://${ip}:${port}`);
|
|
15
|
+
*
|
|
16
|
+
* // Escuchar peticiones
|
|
17
|
+
* await HttpLocalServer.addListener('onRequest', async (data) => {
|
|
18
|
+
* console.log('Petición recibida:', data);
|
|
19
|
+
*
|
|
20
|
+
* // Procesar y responder
|
|
21
|
+
* await HttpLocalServer.sendResponse({
|
|
22
|
+
* requestId: data.requestId,
|
|
23
|
+
* body: JSON.stringify({ success: true })
|
|
24
|
+
* });
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
6
27
|
*/
|
|
7
28
|
declare const HttpLocalServer: HttpLocalServerPlugin;
|
|
8
29
|
export * from './definitions';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,16 +1,34 @@
|
|
|
1
1
|
import { registerPlugin } from '@capacitor/core';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Plugin de servidor HTTP local para Android e iOS.
|
|
4
|
+
*
|
|
5
|
+
* Permite crear un servidor HTTP en el dispositivo que puede recibir
|
|
6
|
+
* peticiones desde otros dispositivos en la misma red.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { HttpLocalServer } from '@cappitolian/http-local-server';
|
|
11
|
+
*
|
|
12
|
+
* // Iniciar servidor
|
|
13
|
+
* const { ip, port } = await HttpLocalServer.connect();
|
|
14
|
+
* console.log(`Servidor en http://${ip}:${port}`);
|
|
15
|
+
*
|
|
16
|
+
* // Escuchar peticiones
|
|
17
|
+
* await HttpLocalServer.addListener('onRequest', async (data) => {
|
|
18
|
+
* console.log('Petición recibida:', data);
|
|
19
|
+
*
|
|
20
|
+
* // Procesar y responder
|
|
21
|
+
* await HttpLocalServer.sendResponse({
|
|
22
|
+
* requestId: data.requestId,
|
|
23
|
+
* body: JSON.stringify({ success: true })
|
|
24
|
+
* });
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
6
27
|
*/
|
|
7
28
|
const HttpLocalServer = registerPlugin('HttpLocalServer', {
|
|
8
29
|
web: () => import('./web').then(m => new m.HttpLocalServerWeb()),
|
|
9
30
|
});
|
|
10
|
-
// Exportamos las interfaces para que el usuario pueda tipar sus variables
|
|
11
31
|
export * from './definitions';
|
|
12
|
-
// Exportamos el objeto del plugin
|
|
13
32
|
export { HttpLocalServer };
|
|
14
|
-
// Exportación por defecto opcional para mayor compatibilidad
|
|
15
33
|
export default HttpLocalServer;
|
|
16
34
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjD
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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,cAAc,eAAe,CAAC;AAC9B,OAAO,EAAE,eAAe,EAAE,CAAC;AAC3B,eAAe,eAAe,CAAC","sourcesContent":["import { registerPlugin } from '@capacitor/core';\nimport type { HttpLocalServerPlugin } from './definitions';\n\n/**\n * Plugin de servidor HTTP local para Android e iOS.\n * \n * Permite crear un servidor HTTP en el dispositivo que puede recibir\n * peticiones desde otros dispositivos en la misma red.\n * \n * @example\n * ```typescript\n * import { HttpLocalServer } from '@cappitolian/http-local-server';\n * \n * // Iniciar servidor\n * const { ip, port } = await HttpLocalServer.connect();\n * console.log(`Servidor en http://${ip}:${port}`);\n * \n * // Escuchar peticiones\n * await HttpLocalServer.addListener('onRequest', async (data) => {\n * console.log('Petición recibida:', data);\n * \n * // Procesar y responder\n * await HttpLocalServer.sendResponse({\n * requestId: data.requestId,\n * body: JSON.stringify({ success: true })\n * });\n * });\n * ```\n */\nconst HttpLocalServer = registerPlugin<HttpLocalServerPlugin>('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\n\nexport * from './definitions';\nexport { HttpLocalServer };\nexport default HttpLocalServer;"]}
|
package/dist/esm/web.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { WebPlugin } from '@capacitor/core';
|
|
2
|
-
import type { HttpLocalServerPlugin, HttpConnectResult } from './definitions';
|
|
2
|
+
import type { HttpLocalServerPlugin, HttpConnectResult, HttpSendResponseOptions } from './definitions';
|
|
3
|
+
/**
|
|
4
|
+
* Implementación web del plugin HttpLocalServer.
|
|
5
|
+
* Proporciona funcionalidad mock para desarrollo en navegador.
|
|
6
|
+
*/
|
|
3
7
|
export declare class HttpLocalServerWeb extends WebPlugin implements HttpLocalServerPlugin {
|
|
8
|
+
private isRunning;
|
|
4
9
|
connect(): Promise<HttpConnectResult>;
|
|
5
10
|
disconnect(): Promise<void>;
|
|
6
|
-
sendResponse(options:
|
|
7
|
-
requestId: string;
|
|
8
|
-
body: string;
|
|
9
|
-
}): Promise<void>;
|
|
11
|
+
sendResponse(options: HttpSendResponseOptions): Promise<void>;
|
|
10
12
|
}
|
package/dist/esm/web.js
CHANGED
|
@@ -1,15 +1,47 @@
|
|
|
1
1
|
import { WebPlugin } from '@capacitor/core';
|
|
2
|
+
/**
|
|
3
|
+
* Implementación web del plugin HttpLocalServer.
|
|
4
|
+
* Proporciona funcionalidad mock para desarrollo en navegador.
|
|
5
|
+
*/
|
|
2
6
|
export class HttpLocalServerWeb extends WebPlugin {
|
|
7
|
+
constructor() {
|
|
8
|
+
super(...arguments);
|
|
9
|
+
this.isRunning = false;
|
|
10
|
+
}
|
|
3
11
|
async connect() {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
12
|
+
if (this.isRunning) {
|
|
13
|
+
console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');
|
|
14
|
+
return { ip: '127.0.0.1', port: 8080 };
|
|
15
|
+
}
|
|
16
|
+
console.warn('HttpLocalServer: El servidor nativo no está disponible en navegador. ' +
|
|
17
|
+
'Retornando valores mock para desarrollo.');
|
|
18
|
+
this.isRunning = true;
|
|
19
|
+
return {
|
|
20
|
+
ip: '127.0.0.1',
|
|
21
|
+
port: 8080
|
|
22
|
+
};
|
|
7
23
|
}
|
|
8
24
|
async disconnect() {
|
|
25
|
+
if (!this.isRunning) {
|
|
26
|
+
console.log('HttpLocalServer: El servidor ya está detenido (Mock).');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
9
29
|
console.log('HttpLocalServer: Servidor detenido (Mock).');
|
|
30
|
+
this.isRunning = false;
|
|
10
31
|
}
|
|
11
32
|
async sendResponse(options) {
|
|
12
|
-
|
|
33
|
+
if (!this.isRunning) {
|
|
34
|
+
console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const { requestId, body } = options;
|
|
38
|
+
if (!requestId) {
|
|
39
|
+
throw new Error('Missing requestId');
|
|
40
|
+
}
|
|
41
|
+
if (!body) {
|
|
42
|
+
throw new Error('Missing body');
|
|
43
|
+
}
|
|
44
|
+
console.log(`HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`, '\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));
|
|
13
45
|
}
|
|
14
46
|
}
|
|
15
47
|
//# sourceMappingURL=web.js.map
|
package/dist/esm/web.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAO5C;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAAjD;;QAEU,cAAS,GAAG,KAAK,CAAC;IAoD5B,CAAC;IAlDC,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;YAC1E,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACzC,CAAC;QAED,OAAO,CAAC,IAAI,CACV,uEAAuE;YACvE,0CAA0C,CAC3C,CAAC;QAEF,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,OAAO;YACL,EAAE,EAAE,WAAW;YACf,IAAI,EAAE,IAAI;SACX,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,UAAU;QACd,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC,CAAC;YACrE,OAAO;QACT,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;QAC1D,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAAgC;QACjD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;YAC1E,OAAO;QACT,CAAC;QAED,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAEpC,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACvC,CAAC;QAED,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;QAClC,CAAC;QAED,OAAO,CAAC,GAAG,CACT,2DAA2D,SAAS,EAAE,EACtE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CACrE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\nimport type {\n HttpLocalServerPlugin,\n HttpConnectResult,\n HttpSendResponseOptions\n} from './definitions';\n\n/**\n * Implementación web del plugin HttpLocalServer.\n * Proporciona funcionalidad mock para desarrollo en navegador.\n */\nexport class HttpLocalServerWeb extends WebPlugin implements HttpLocalServerPlugin {\n\n private isRunning = false;\n\n async connect(): Promise<HttpConnectResult> {\n if (this.isRunning) {\n console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');\n return { ip: '127.0.0.1', port: 8080 };\n }\n\n console.warn(\n 'HttpLocalServer: El servidor nativo no está disponible en navegador. ' +\n 'Retornando valores mock para desarrollo.'\n );\n\n this.isRunning = true;\n\n return {\n ip: '127.0.0.1',\n port: 8080\n };\n }\n\n async disconnect(): Promise<void> {\n if (!this.isRunning) {\n console.log('HttpLocalServer: El servidor ya está detenido (Mock).');\n return;\n }\n\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n this.isRunning = false;\n }\n\n async sendResponse(options: HttpSendResponseOptions): Promise<void> {\n if (!this.isRunning) {\n console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');\n return;\n }\n\n const { requestId, body } = options;\n\n if (!requestId) {\n throw new Error('Missing requestId');\n }\n\n if (!body) {\n throw new Error('Missing body');\n }\n\n console.log(\n `HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`,\n '\\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : '')\n );\n }\n}"]}
|
package/dist/plugin.cjs.js
CHANGED
|
@@ -5,25 +5,78 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
5
5
|
var core = require('@capacitor/core');
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* Plugin de servidor HTTP local para Android e iOS.
|
|
9
|
+
*
|
|
10
|
+
* Permite crear un servidor HTTP en el dispositivo que puede recibir
|
|
11
|
+
* peticiones desde otros dispositivos en la misma red.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { HttpLocalServer } from '@cappitolian/http-local-server';
|
|
16
|
+
*
|
|
17
|
+
* // Iniciar servidor
|
|
18
|
+
* const { ip, port } = await HttpLocalServer.connect();
|
|
19
|
+
* console.log(`Servidor en http://${ip}:${port}`);
|
|
20
|
+
*
|
|
21
|
+
* // Escuchar peticiones
|
|
22
|
+
* await HttpLocalServer.addListener('onRequest', async (data) => {
|
|
23
|
+
* console.log('Petición recibida:', data);
|
|
24
|
+
*
|
|
25
|
+
* // Procesar y responder
|
|
26
|
+
* await HttpLocalServer.sendResponse({
|
|
27
|
+
* requestId: data.requestId,
|
|
28
|
+
* body: JSON.stringify({ success: true })
|
|
29
|
+
* });
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
11
32
|
*/
|
|
12
33
|
const HttpLocalServer = core.registerPlugin('HttpLocalServer', {
|
|
13
34
|
web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpLocalServerWeb()),
|
|
14
35
|
});
|
|
15
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Implementación web del plugin HttpLocalServer.
|
|
39
|
+
* Proporciona funcionalidad mock para desarrollo en navegador.
|
|
40
|
+
*/
|
|
16
41
|
class HttpLocalServerWeb extends core.WebPlugin {
|
|
42
|
+
constructor() {
|
|
43
|
+
super(...arguments);
|
|
44
|
+
this.isRunning = false;
|
|
45
|
+
}
|
|
17
46
|
async connect() {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
47
|
+
if (this.isRunning) {
|
|
48
|
+
console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');
|
|
49
|
+
return { ip: '127.0.0.1', port: 8080 };
|
|
50
|
+
}
|
|
51
|
+
console.warn('HttpLocalServer: El servidor nativo no está disponible en navegador. ' +
|
|
52
|
+
'Retornando valores mock para desarrollo.');
|
|
53
|
+
this.isRunning = true;
|
|
54
|
+
return {
|
|
55
|
+
ip: '127.0.0.1',
|
|
56
|
+
port: 8080
|
|
57
|
+
};
|
|
21
58
|
}
|
|
22
59
|
async disconnect() {
|
|
60
|
+
if (!this.isRunning) {
|
|
61
|
+
console.log('HttpLocalServer: El servidor ya está detenido (Mock).');
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
23
64
|
console.log('HttpLocalServer: Servidor detenido (Mock).');
|
|
65
|
+
this.isRunning = false;
|
|
24
66
|
}
|
|
25
67
|
async sendResponse(options) {
|
|
26
|
-
|
|
68
|
+
if (!this.isRunning) {
|
|
69
|
+
console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const { requestId, body } = options;
|
|
73
|
+
if (!requestId) {
|
|
74
|
+
throw new Error('Missing requestId');
|
|
75
|
+
}
|
|
76
|
+
if (!body) {
|
|
77
|
+
throw new Error('Missing body');
|
|
78
|
+
}
|
|
79
|
+
console.log(`HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`, '\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));
|
|
27
80
|
}
|
|
28
81
|
}
|
|
29
82
|
|
package/dist/plugin.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n *
|
|
1
|
+
{"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n * Plugin de servidor HTTP local para Android e iOS.\n *\n * Permite crear un servidor HTTP en el dispositivo que puede recibir\n * peticiones desde otros dispositivos en la misma red.\n *\n * @example\n * ```typescript\n * import { HttpLocalServer } from '@cappitolian/http-local-server';\n *\n * // Iniciar servidor\n * const { ip, port } = await HttpLocalServer.connect();\n * console.log(`Servidor en http://${ip}:${port}`);\n *\n * // Escuchar peticiones\n * await HttpLocalServer.addListener('onRequest', async (data) => {\n * console.log('Petición recibida:', data);\n *\n * // Procesar y responder\n * await HttpLocalServer.sendResponse({\n * requestId: data.requestId,\n * body: JSON.stringify({ success: true })\n * });\n * });\n * ```\n */\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\nexport * from './definitions';\nexport { HttpLocalServer };\nexport default HttpLocalServer;\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Implementación web del plugin HttpLocalServer.\n * Proporciona funcionalidad mock para desarrollo en navegador.\n */\nexport class HttpLocalServerWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.isRunning = false;\n }\n async connect() {\n if (this.isRunning) {\n console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');\n return { ip: '127.0.0.1', port: 8080 };\n }\n console.warn('HttpLocalServer: El servidor nativo no está disponible en navegador. ' +\n 'Retornando valores mock para desarrollo.');\n this.isRunning = true;\n return {\n ip: '127.0.0.1',\n port: 8080\n };\n }\n async disconnect() {\n if (!this.isRunning) {\n console.log('HttpLocalServer: El servidor ya está detenido (Mock).');\n return;\n }\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n this.isRunning = false;\n }\n async sendResponse(options) {\n if (!this.isRunning) {\n console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');\n return;\n }\n const { requestId, body } = options;\n if (!requestId) {\n throw new Error('Missing requestId');\n }\n if (!body) {\n throw new Error('Missing body');\n }\n console.log(`HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`, '\\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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;;AC5BD;AACA;AACA;AACA;AACO,MAAM,kBAAkB,SAASC,cAAS,CAAC;AAClD,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,GAAG,SAAS,CAAC;AAC3B,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK;AAC9B,IAAI;AACJ,IAAI,MAAM,OAAO,GAAG;AACpB,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE;AAC5B,YAAY,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC;AACrF,YAAY,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE;AAClD,QAAQ;AACR,QAAQ,OAAO,CAAC,IAAI,CAAC,uEAAuE;AAC5F,YAAY,0CAA0C,CAAC;AACvD,QAAQ,IAAI,CAAC,SAAS,GAAG,IAAI;AAC7B,QAAQ,OAAO;AACf,YAAY,EAAE,EAAE,WAAW;AAC3B,YAAY,IAAI,EAAE;AAClB,SAAS;AACT,IAAI;AACJ,IAAI,MAAM,UAAU,GAAG;AACvB,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;AAC7B,YAAY,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC;AAChF,YAAY;AACZ,QAAQ;AACR,QAAQ,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;AACjE,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK;AAC9B,IAAI;AACJ,IAAI,MAAM,YAAY,CAAC,OAAO,EAAE;AAChC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;AAC7B,YAAY,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC;AACrF,YAAY;AACZ,QAAQ;AACR,QAAQ,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,OAAO;AAC3C,QAAQ,IAAI,CAAC,SAAS,EAAE;AACxB,YAAY,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC;AAChD,QAAQ;AACR,QAAQ,IAAI,CAAC,IAAI,EAAE;AACnB,YAAY,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC;AAC3C,QAAQ;AACR,QAAQ,OAAO,CAAC,GAAG,CAAC,CAAC,wDAAwD,EAAE,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,GAAG,EAAE,CAAC,CAAC;AACjK,IAAI;AACJ;;;;;;;;;;"}
|
package/dist/plugin.js
CHANGED
|
@@ -2,25 +2,78 @@ var capacitorHttpLocalServer = (function (exports, core) {
|
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* Plugin de servidor HTTP local para Android e iOS.
|
|
6
|
+
*
|
|
7
|
+
* Permite crear un servidor HTTP en el dispositivo que puede recibir
|
|
8
|
+
* peticiones desde otros dispositivos en la misma red.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { HttpLocalServer } from '@cappitolian/http-local-server';
|
|
13
|
+
*
|
|
14
|
+
* // Iniciar servidor
|
|
15
|
+
* const { ip, port } = await HttpLocalServer.connect();
|
|
16
|
+
* console.log(`Servidor en http://${ip}:${port}`);
|
|
17
|
+
*
|
|
18
|
+
* // Escuchar peticiones
|
|
19
|
+
* await HttpLocalServer.addListener('onRequest', async (data) => {
|
|
20
|
+
* console.log('Petición recibida:', data);
|
|
21
|
+
*
|
|
22
|
+
* // Procesar y responder
|
|
23
|
+
* await HttpLocalServer.sendResponse({
|
|
24
|
+
* requestId: data.requestId,
|
|
25
|
+
* body: JSON.stringify({ success: true })
|
|
26
|
+
* });
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
8
29
|
*/
|
|
9
30
|
const HttpLocalServer = core.registerPlugin('HttpLocalServer', {
|
|
10
31
|
web: () => Promise.resolve().then(function () { return web; }).then(m => new m.HttpLocalServerWeb()),
|
|
11
32
|
});
|
|
12
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Implementación web del plugin HttpLocalServer.
|
|
36
|
+
* Proporciona funcionalidad mock para desarrollo en navegador.
|
|
37
|
+
*/
|
|
13
38
|
class HttpLocalServerWeb extends core.WebPlugin {
|
|
39
|
+
constructor() {
|
|
40
|
+
super(...arguments);
|
|
41
|
+
this.isRunning = false;
|
|
42
|
+
}
|
|
14
43
|
async connect() {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
44
|
+
if (this.isRunning) {
|
|
45
|
+
console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');
|
|
46
|
+
return { ip: '127.0.0.1', port: 8080 };
|
|
47
|
+
}
|
|
48
|
+
console.warn('HttpLocalServer: El servidor nativo no está disponible en navegador. ' +
|
|
49
|
+
'Retornando valores mock para desarrollo.');
|
|
50
|
+
this.isRunning = true;
|
|
51
|
+
return {
|
|
52
|
+
ip: '127.0.0.1',
|
|
53
|
+
port: 8080
|
|
54
|
+
};
|
|
18
55
|
}
|
|
19
56
|
async disconnect() {
|
|
57
|
+
if (!this.isRunning) {
|
|
58
|
+
console.log('HttpLocalServer: El servidor ya está detenido (Mock).');
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
20
61
|
console.log('HttpLocalServer: Servidor detenido (Mock).');
|
|
62
|
+
this.isRunning = false;
|
|
21
63
|
}
|
|
22
64
|
async sendResponse(options) {
|
|
23
|
-
|
|
65
|
+
if (!this.isRunning) {
|
|
66
|
+
console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const { requestId, body } = options;
|
|
70
|
+
if (!requestId) {
|
|
71
|
+
throw new Error('Missing requestId');
|
|
72
|
+
}
|
|
73
|
+
if (!body) {
|
|
74
|
+
throw new Error('Missing body');
|
|
75
|
+
}
|
|
76
|
+
console.log(`HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`, '\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));
|
|
24
77
|
}
|
|
25
78
|
}
|
|
26
79
|
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n *
|
|
1
|
+
{"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\n/**\n * Plugin de servidor HTTP local para Android e iOS.\n *\n * Permite crear un servidor HTTP en el dispositivo que puede recibir\n * peticiones desde otros dispositivos en la misma red.\n *\n * @example\n * ```typescript\n * import { HttpLocalServer } from '@cappitolian/http-local-server';\n *\n * // Iniciar servidor\n * const { ip, port } = await HttpLocalServer.connect();\n * console.log(`Servidor en http://${ip}:${port}`);\n *\n * // Escuchar peticiones\n * await HttpLocalServer.addListener('onRequest', async (data) => {\n * console.log('Petición recibida:', data);\n *\n * // Procesar y responder\n * await HttpLocalServer.sendResponse({\n * requestId: data.requestId,\n * body: JSON.stringify({ success: true })\n * });\n * });\n * ```\n */\nconst HttpLocalServer = registerPlugin('HttpLocalServer', {\n web: () => import('./web').then(m => new m.HttpLocalServerWeb()),\n});\nexport * from './definitions';\nexport { HttpLocalServer };\nexport default HttpLocalServer;\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\n/**\n * Implementación web del plugin HttpLocalServer.\n * Proporciona funcionalidad mock para desarrollo en navegador.\n */\nexport class HttpLocalServerWeb extends WebPlugin {\n constructor() {\n super(...arguments);\n this.isRunning = false;\n }\n async connect() {\n if (this.isRunning) {\n console.warn('HttpLocalServer: El servidor ya está ejecutándose (Mock).');\n return { ip: '127.0.0.1', port: 8080 };\n }\n console.warn('HttpLocalServer: El servidor nativo no está disponible en navegador. ' +\n 'Retornando valores mock para desarrollo.');\n this.isRunning = true;\n return {\n ip: '127.0.0.1',\n port: 8080\n };\n }\n async disconnect() {\n if (!this.isRunning) {\n console.log('HttpLocalServer: El servidor ya está detenido (Mock).');\n return;\n }\n console.log('HttpLocalServer: Servidor detenido (Mock).');\n this.isRunning = false;\n }\n async sendResponse(options) {\n if (!this.isRunning) {\n console.warn('HttpLocalServer: El servidor no está ejecutándose (Mock).');\n return;\n }\n const { requestId, body } = options;\n if (!requestId) {\n throw new Error('Missing requestId');\n }\n if (!body) {\n throw new Error('Missing body');\n }\n console.log(`HttpLocalServer: Respuesta mock enviada para requestId: ${requestId}`, '\\nBody:', body.substring(0, 100) + (body.length > 100 ? '...' : ''));\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;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;;IC5BD;IACA;IACA;IACA;IACO,MAAM,kBAAkB,SAASC,cAAS,CAAC;IAClD,IAAI,WAAW,GAAG;IAClB,QAAQ,KAAK,CAAC,GAAG,SAAS,CAAC;IAC3B,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK;IAC9B,IAAI;IACJ,IAAI,MAAM,OAAO,GAAG;IACpB,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE;IAC5B,YAAY,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC;IACrF,YAAY,OAAO,EAAE,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE;IAClD,QAAQ;IACR,QAAQ,OAAO,CAAC,IAAI,CAAC,uEAAuE;IAC5F,YAAY,0CAA0C,CAAC;IACvD,QAAQ,IAAI,CAAC,SAAS,GAAG,IAAI;IAC7B,QAAQ,OAAO;IACf,YAAY,EAAE,EAAE,WAAW;IAC3B,YAAY,IAAI,EAAE;IAClB,SAAS;IACT,IAAI;IACJ,IAAI,MAAM,UAAU,GAAG;IACvB,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;IAC7B,YAAY,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC;IAChF,YAAY;IACZ,QAAQ;IACR,QAAQ,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;IACjE,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK;IAC9B,IAAI;IACJ,IAAI,MAAM,YAAY,CAAC,OAAO,EAAE;IAChC,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;IAC7B,YAAY,OAAO,CAAC,IAAI,CAAC,2DAA2D,CAAC;IACrF,YAAY;IACZ,QAAQ;IACR,QAAQ,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,GAAG,OAAO;IAC3C,QAAQ,IAAI,CAAC,SAAS,EAAE;IACxB,YAAY,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC;IAChD,QAAQ;IACR,QAAQ,IAAI,CAAC,IAAI,EAAE;IACnB,YAAY,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC;IAC3C,QAAQ;IACR,QAAQ,OAAO,CAAC,GAAG,CAAC,CAAC,wDAAwD,EAAE,SAAS,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,GAAG,KAAK,GAAG,EAAE,CAAC,CAAC;IACjK,IAAI;IACJ;;;;;;;;;;;;;;;;;;"}
|
|
@@ -27,6 +27,7 @@ public protocol HttpLocalServerDelegate: AnyObject {
|
|
|
27
27
|
|
|
28
28
|
// MARK: - HttpLocalServer
|
|
29
29
|
@objc public class HttpLocalServer: NSObject {
|
|
30
|
+
|
|
30
31
|
// MARK: - Properties
|
|
31
32
|
private var webServer: GCDWebServer?
|
|
32
33
|
private weak var delegate: HttpLocalServerDelegate?
|
|
@@ -194,7 +195,8 @@ public protocol HttpLocalServerDelegate: AnyObject {
|
|
|
194
195
|
"path": path
|
|
195
196
|
]
|
|
196
197
|
|
|
197
|
-
|
|
198
|
+
// Solo agregar si existen (consistente con TypeScript y Android)
|
|
199
|
+
if let body = body, !body.isEmpty {
|
|
198
200
|
requestData["body"] = body
|
|
199
201
|
}
|
|
200
202
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cappitolian/http-local-server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
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",
|