swarpc 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"swarpc.d.ts","sourceRoot":"","sources":["../src/swarpc.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAA;AAEnB,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE3E,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EAAE,MAAM,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,YAAY,CAAC,UAAU,CAAC,CAyE1B;AA4DD,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EAAE,MAAM,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,YAAY,CAAC,UAAU,CAAC,CAmC1B"}
1
+ {"version":3,"file":"swarpc.d.ts","sourceRoot":"","sources":["../src/swarpc.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,YAAY,EAClB,MAAM,YAAY,CAAA;AAEnB,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE3E,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EAAE,MAAM,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,YAAY,CAAC,UAAU,CAAC,CA+E1B;AA4DD,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EAAE,MAAM,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GACnC,YAAY,CAAC,UAAU,CAAC,CAyC1B"}
package/dist/swarpc.js CHANGED
@@ -32,6 +32,7 @@ export function Server(procedures, { worker } = {}) {
32
32
  };
33
33
  self.addEventListener("message", async (event) => {
34
34
  const { functionName, requestId, input } = PayloadSchema.assert(event.data);
35
+ l.server.debug(requestId, `Received request for ${functionName}`, input);
35
36
  const postError = async (error) => postMessage({
36
37
  functionName,
37
38
  requestId,
@@ -45,12 +46,15 @@ export function Server(procedures, { worker } = {}) {
45
46
  return;
46
47
  }
47
48
  await implementation(input, async (progress) => {
49
+ l.server.debug(requestId, `Progress for ${functionName}`, progress);
48
50
  await postMessage({ functionName, requestId, progress });
49
51
  })
50
52
  .catch(async (error) => {
53
+ l.server.error(requestId, `Error in ${functionName}`, error);
51
54
  await postError(error);
52
55
  })
53
56
  .then(async (result) => {
57
+ l.server.debug(requestId, `Result for ${functionName}`, result);
54
58
  await postMessage({ functionName, requestId, result });
55
59
  });
56
60
  });
@@ -58,7 +62,7 @@ export function Server(procedures, { worker } = {}) {
58
62
  return instance;
59
63
  }
60
64
  function generateRequestId() {
61
- return Math.random().toString(36).substring(2, 15);
65
+ return Math.random().toString(16).substring(2, 8).toUpperCase();
62
66
  }
63
67
  const pendingRequests = new Map();
64
68
  let _clientListenerStarted = false;
@@ -71,11 +75,11 @@ async function startClientListener(worker) {
71
75
  throw new Error("[SWARPC Client] Service Worker is not active");
72
76
  }
73
77
  if (!navigator.serviceWorker.controller) {
74
- console.warn("[SWARPC Client] Service Worker is not controlling the page");
78
+ l.client.warn("", "Service Worker is not controlling the page");
75
79
  }
76
80
  }
77
81
  const w = worker ?? navigator.serviceWorker;
78
- console.log("[SWARPC Client] Starting client listener on", w);
82
+ l.client.debug("", "Starting client listener on", w);
79
83
  w.addEventListener("message", (event) => {
80
84
  const { functionName, requestId, ...data } = event.data || {};
81
85
  if (!requestId) {
@@ -102,6 +106,10 @@ async function startClientListener(worker) {
102
106
  export function Client(procedures, { worker } = {}) {
103
107
  const instance = { [zProcedures]: procedures };
104
108
  for (const functionName of Object.keys(procedures)) {
109
+ if (typeof functionName !== "string") {
110
+ throw new Error(`[SWARPC Client] Invalid function name, don't use symbols`);
111
+ }
112
+ // @ts-expect-error
105
113
  instance[functionName] = (async (input, onProgress = () => { }) => {
106
114
  procedures[functionName].input.assert(input);
107
115
  await startClientListener(worker);
@@ -111,12 +119,45 @@ export function Client(procedures, { worker } = {}) {
111
119
  }
112
120
  return new Promise((resolve, reject) => {
113
121
  if (!worker && !navigator.serviceWorker.controller)
114
- console.warn("[SWARPC Client] Service Worker is not controlling the page");
122
+ l.client.warn("", "Service Worker is not controlling the page");
115
123
  const requestId = generateRequestId();
116
124
  pendingRequests.set(requestId, { resolve, onProgress, reject });
125
+ l.client.debug(requestId, `Requesting ${functionName} with`, input);
117
126
  w.postMessage({ functionName, input, requestId });
118
127
  });
119
128
  });
120
129
  }
121
130
  return instance;
122
131
  }
132
+ const l = {
133
+ server: {
134
+ debug: (rqid, message, ...args) => log("debug", "server", rqid, message, ...args),
135
+ info: (rqid, message, ...args) => log("info", "server", rqid, message, ...args),
136
+ warn: (rqid, message, ...args) => log("warn", "server", rqid, message, ...args),
137
+ error: (rqid, message, ...args) => log("error", "server", rqid, message, ...args),
138
+ },
139
+ client: {
140
+ debug: (rqid, message, ...args) => log("debug", "client", rqid, message, ...args),
141
+ info: (rqid, message, ...args) => log("info", "client", rqid, message, ...args),
142
+ warn: (rqid, message, ...args) => log("warn", "client", rqid, message, ...args),
143
+ error: (rqid, message, ...args) => log("error", "client", rqid, message, ...args),
144
+ },
145
+ };
146
+ function log(severity, side, rqid, message, ...args) {
147
+ const prefix = "[" +
148
+ ["SWARPC", side, rqid ? `%c${rqid}%c` : ""].filter(Boolean).join(" ") +
149
+ "]";
150
+ const prefixStyles = rqid ? ["color: cyan;", "color: inherit;"] : [];
151
+ if (severity === "debug") {
152
+ console.debug(prefix, ...prefixStyles, message, ...args);
153
+ }
154
+ else if (severity === "info") {
155
+ console.info(prefix, ...prefixStyles, message, ...args);
156
+ }
157
+ else if (severity === "warn") {
158
+ console.warn(prefix, ...prefixStyles, message, ...args);
159
+ }
160
+ else if (severity === "error") {
161
+ console.error(prefix, ...prefixStyles, message, ...args);
162
+ }
163
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swarpc",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Full type-safe RPC library for service worker -- move things off of the UI thread with ease!",
5
5
  "keywords": [
6
6
  "service-workers",
package/src/swarpc.ts CHANGED
@@ -58,6 +58,9 @@ export function Server<Procedures extends ProceduresMap>(
58
58
  const { functionName, requestId, input } = PayloadSchema.assert(
59
59
  event.data
60
60
  )
61
+
62
+ l.server.debug(requestId, `Received request for ${functionName}`, input)
63
+
61
64
  const postError = async (error: any) =>
62
65
  postMessage({
63
66
  functionName,
@@ -74,12 +77,15 @@ export function Server<Procedures extends ProceduresMap>(
74
77
  }
75
78
 
76
79
  await implementation(input, async (progress: any) => {
80
+ l.server.debug(requestId, `Progress for ${functionName}`, progress)
77
81
  await postMessage({ functionName, requestId, progress })
78
82
  })
79
83
  .catch(async (error: any) => {
84
+ l.server.error(requestId, `Error in ${functionName}`, error)
80
85
  await postError(error)
81
86
  })
82
87
  .then(async (result: any) => {
88
+ l.server.debug(requestId, `Result for ${functionName}`, result)
83
89
  await postMessage({ functionName, requestId, result })
84
90
  })
85
91
  })
@@ -89,7 +95,7 @@ export function Server<Procedures extends ProceduresMap>(
89
95
  }
90
96
 
91
97
  function generateRequestId(): string {
92
- return Math.random().toString(36).substring(2, 15)
98
+ return Math.random().toString(16).substring(2, 8).toUpperCase()
93
99
  }
94
100
 
95
101
  type PendingRequest = {
@@ -111,12 +117,12 @@ async function startClientListener(worker?: Worker) {
111
117
  }
112
118
 
113
119
  if (!navigator.serviceWorker.controller) {
114
- console.warn("[SWARPC Client] Service Worker is not controlling the page")
120
+ l.client.warn("", "Service Worker is not controlling the page")
115
121
  }
116
122
  }
117
123
 
118
124
  const w = worker ?? navigator.serviceWorker
119
- console.log("[SWARPC Client] Starting client listener on", w)
125
+ l.client.debug("", "Starting client listener on", w)
120
126
  w.addEventListener("message", (event) => {
121
127
  const { functionName, requestId, ...data } =
122
128
  (event as MessageEvent).data || {}
@@ -157,6 +163,13 @@ export function Client<Procedures extends ProceduresMap>(
157
163
  for (const functionName of Object.keys(procedures) as Array<
158
164
  keyof Procedures
159
165
  >) {
166
+ if (typeof functionName !== "string") {
167
+ throw new Error(
168
+ `[SWARPC Client] Invalid function name, don't use symbols`
169
+ )
170
+ }
171
+
172
+ // @ts-expect-error
160
173
  instance[functionName] = (async (input: unknown, onProgress = () => {}) => {
161
174
  procedures[functionName].input.assert(input)
162
175
  await startClientListener(worker)
@@ -170,14 +183,13 @@ export function Client<Procedures extends ProceduresMap>(
170
183
 
171
184
  return new Promise((resolve, reject) => {
172
185
  if (!worker && !navigator.serviceWorker.controller)
173
- console.warn(
174
- "[SWARPC Client] Service Worker is not controlling the page"
175
- )
186
+ l.client.warn("", "Service Worker is not controlling the page")
176
187
 
177
188
  const requestId = generateRequestId()
178
189
 
179
190
  pendingRequests.set(requestId, { resolve, onProgress, reject })
180
191
 
192
+ l.client.debug(requestId, `Requesting ${functionName} with`, input)
181
193
  w.postMessage({ functionName, input, requestId })
182
194
  })
183
195
  }) as SwarpcClient<Procedures>[typeof functionName]
@@ -185,3 +197,51 @@ export function Client<Procedures extends ProceduresMap>(
185
197
 
186
198
  return instance as SwarpcClient<Procedures>
187
199
  }
200
+
201
+ const l = {
202
+ server: {
203
+ debug: (rqid: string | null, message: string, ...args: any[]) =>
204
+ log("debug", "server", rqid, message, ...args),
205
+ info: (rqid: string | null, message: string, ...args: any[]) =>
206
+ log("info", "server", rqid, message, ...args),
207
+ warn: (rqid: string | null, message: string, ...args: any[]) =>
208
+ log("warn", "server", rqid, message, ...args),
209
+ error: (rqid: string | null, message: string, ...args: any[]) =>
210
+ log("error", "server", rqid, message, ...args),
211
+ },
212
+ client: {
213
+ debug: (rqid: string | null, message: string, ...args: any[]) =>
214
+ log("debug", "client", rqid, message, ...args),
215
+ info: (rqid: string | null, message: string, ...args: any[]) =>
216
+ log("info", "client", rqid, message, ...args),
217
+ warn: (rqid: string | null, message: string, ...args: any[]) =>
218
+ log("warn", "client", rqid, message, ...args),
219
+ error: (rqid: string | null, message: string, ...args: any[]) =>
220
+ log("error", "client", rqid, message, ...args),
221
+ },
222
+ }
223
+
224
+ function log(
225
+ severity: "debug" | "info" | "warn" | "error",
226
+ side: "server" | "client",
227
+ rqid: string | null,
228
+ message: string,
229
+ ...args: any[]
230
+ ) {
231
+ const prefix =
232
+ "[" +
233
+ ["SWARPC", side, rqid ? `%c${rqid}%c` : ""].filter(Boolean).join(" ") +
234
+ "]"
235
+
236
+ const prefixStyles = rqid ? ["color: cyan;", "color: inherit;"] : []
237
+
238
+ if (severity === "debug") {
239
+ console.debug(prefix, ...prefixStyles, message, ...args)
240
+ } else if (severity === "info") {
241
+ console.info(prefix, ...prefixStyles, message, ...args)
242
+ } else if (severity === "warn") {
243
+ console.warn(prefix, ...prefixStyles, message, ...args)
244
+ } else if (severity === "error") {
245
+ console.error(prefix, ...prefixStyles, message, ...args)
246
+ }
247
+ }