@supertokens-plugins/rownd-nodejs 0.2.0 → 0.2.1

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/dist/index.js ADDED
@@ -0,0 +1,1109 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // ../../node_modules/supertokens-js-override/lib/build/getProxyObject.js
34
+ var require_getProxyObject = __commonJS({
35
+ "../../node_modules/supertokens-js-override/lib/build/getProxyObject.js"(exports2) {
36
+ "use strict";
37
+ var __assign = exports2 && exports2.__assign || function() {
38
+ __assign = Object.assign || function(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
42
+ t[p] = s[p];
43
+ }
44
+ return t;
45
+ };
46
+ return __assign.apply(this, arguments);
47
+ };
48
+ Object.defineProperty(exports2, "__esModule", { value: true });
49
+ exports2.getProxyObject = void 0;
50
+ function getProxyObject(orig) {
51
+ var ret = __assign(__assign({}, orig), { _call: function(_, __) {
52
+ throw new Error("This function should only be called through the recipe object");
53
+ } });
54
+ var keys = Object.keys(ret);
55
+ var _loop_1 = function(k2) {
56
+ if (k2 !== "_call") {
57
+ ret[k2] = function() {
58
+ var args = [];
59
+ for (var _i2 = 0; _i2 < arguments.length; _i2++) {
60
+ args[_i2] = arguments[_i2];
61
+ }
62
+ return this._call(k2, args);
63
+ };
64
+ }
65
+ };
66
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
67
+ var k = keys_1[_i];
68
+ _loop_1(k);
69
+ }
70
+ return ret;
71
+ }
72
+ exports2.getProxyObject = getProxyObject;
73
+ }
74
+ });
75
+
76
+ // ../../node_modules/supertokens-js-override/lib/build/index.js
77
+ var require_build = __commonJS({
78
+ "../../node_modules/supertokens-js-override/lib/build/index.js"(exports2) {
79
+ "use strict";
80
+ Object.defineProperty(exports2, "__esModule", { value: true });
81
+ exports2.OverrideableBuilder = void 0;
82
+ var getProxyObject_1 = require_getProxyObject();
83
+ var OverrideableBuilder2 = (
84
+ /** @class */
85
+ (function() {
86
+ function OverrideableBuilder3(originalImplementation) {
87
+ this.layers = [originalImplementation];
88
+ this.proxies = [];
89
+ }
90
+ OverrideableBuilder3.prototype.override = function(overrideFunc) {
91
+ var proxy = (0, getProxyObject_1.getProxyObject)(this.layers[0]);
92
+ var layer = overrideFunc(proxy, this);
93
+ for (var _i = 0, _a = Object.keys(this.layers[0]); _i < _a.length; _i++) {
94
+ var key = _a[_i];
95
+ if (layer[key] === proxy[key] || key === "_call") {
96
+ delete layer[key];
97
+ } else if (layer[key] === void 0) {
98
+ layer[key] = null;
99
+ }
100
+ }
101
+ this.layers.push(layer);
102
+ this.proxies.push(proxy);
103
+ return this;
104
+ };
105
+ OverrideableBuilder3.prototype.build = function() {
106
+ var _this = this;
107
+ if (this.result) {
108
+ return this.result;
109
+ }
110
+ this.result = {};
111
+ for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
112
+ var layer = _a[_i];
113
+ for (var _b = 0, _c = Object.keys(layer); _b < _c.length; _b++) {
114
+ var key = _c[_b];
115
+ var override = layer[key];
116
+ if (override !== void 0) {
117
+ if (override === null) {
118
+ this.result[key] = void 0;
119
+ } else if (typeof override === "function") {
120
+ this.result[key] = override.bind(this.result);
121
+ } else {
122
+ this.result[key] = override;
123
+ }
124
+ }
125
+ }
126
+ }
127
+ var _loop_1 = function(proxyInd2) {
128
+ var proxy = this_1.proxies[proxyInd2];
129
+ proxy._call = function(fname, args) {
130
+ for (var i = proxyInd2; i >= 0; --i) {
131
+ var func = _this.layers[i][fname];
132
+ if (func !== void 0 && func !== null) {
133
+ return func.bind(_this.result).apply(void 0, args);
134
+ }
135
+ }
136
+ };
137
+ };
138
+ var this_1 = this;
139
+ for (var proxyInd = 0; proxyInd < this.proxies.length; ++proxyInd) {
140
+ _loop_1(proxyInd);
141
+ }
142
+ return this.result;
143
+ };
144
+ return OverrideableBuilder3;
145
+ })()
146
+ );
147
+ exports2.OverrideableBuilder = OverrideableBuilder2;
148
+ exports2.default = OverrideableBuilder2;
149
+ }
150
+ });
151
+
152
+ // ../../node_modules/has-flag/index.js
153
+ var require_has_flag = __commonJS({
154
+ "../../node_modules/has-flag/index.js"(exports2, module2) {
155
+ "use strict";
156
+ module2.exports = (flag, argv = process.argv) => {
157
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
158
+ const position = argv.indexOf(prefix + flag);
159
+ const terminatorPosition = argv.indexOf("--");
160
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
161
+ };
162
+ }
163
+ });
164
+
165
+ // ../../node_modules/supports-color/index.js
166
+ var require_supports_color = __commonJS({
167
+ "../../node_modules/supports-color/index.js"(exports2, module2) {
168
+ "use strict";
169
+ var os = require("os");
170
+ var tty = require("tty");
171
+ var hasFlag = require_has_flag();
172
+ var { env } = process;
173
+ var forceColor;
174
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
175
+ forceColor = 0;
176
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
177
+ forceColor = 1;
178
+ }
179
+ if ("FORCE_COLOR" in env) {
180
+ if (env.FORCE_COLOR === "true") {
181
+ forceColor = 1;
182
+ } else if (env.FORCE_COLOR === "false") {
183
+ forceColor = 0;
184
+ } else {
185
+ forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
186
+ }
187
+ }
188
+ function translateLevel(level) {
189
+ if (level === 0) {
190
+ return false;
191
+ }
192
+ return {
193
+ level,
194
+ hasBasic: true,
195
+ has256: level >= 2,
196
+ has16m: level >= 3
197
+ };
198
+ }
199
+ function supportsColor(haveStream, streamIsTTY) {
200
+ if (forceColor === 0) {
201
+ return 0;
202
+ }
203
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
204
+ return 3;
205
+ }
206
+ if (hasFlag("color=256")) {
207
+ return 2;
208
+ }
209
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
210
+ return 0;
211
+ }
212
+ const min = forceColor || 0;
213
+ if (env.TERM === "dumb") {
214
+ return min;
215
+ }
216
+ if (process.platform === "win32") {
217
+ const osRelease = os.release().split(".");
218
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
219
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
220
+ }
221
+ return 1;
222
+ }
223
+ if ("CI" in env) {
224
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
225
+ return 1;
226
+ }
227
+ return min;
228
+ }
229
+ if ("TEAMCITY_VERSION" in env) {
230
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
231
+ }
232
+ if (env.COLORTERM === "truecolor") {
233
+ return 3;
234
+ }
235
+ if ("TERM_PROGRAM" in env) {
236
+ const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
237
+ switch (env.TERM_PROGRAM) {
238
+ case "iTerm.app":
239
+ return version >= 3 ? 3 : 2;
240
+ case "Apple_Terminal":
241
+ return 2;
242
+ }
243
+ }
244
+ if (/-256(color)?$/i.test(env.TERM)) {
245
+ return 2;
246
+ }
247
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
248
+ return 1;
249
+ }
250
+ if ("COLORTERM" in env) {
251
+ return 1;
252
+ }
253
+ return min;
254
+ }
255
+ function getSupportLevel(stream) {
256
+ const level = supportsColor(stream, stream && stream.isTTY);
257
+ return translateLevel(level);
258
+ }
259
+ module2.exports = {
260
+ supportsColor: getSupportLevel,
261
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
262
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
263
+ };
264
+ }
265
+ });
266
+
267
+ // src/index.ts
268
+ var index_exports = {};
269
+ __export(index_exports, {
270
+ HANDLE_BASE_PATH: () => HANDLE_BASE_PATH,
271
+ PLUGIN_ID: () => PLUGIN_ID,
272
+ PLUGIN_SDK_VERSION: () => PLUGIN_SDK_VERSION,
273
+ PUBLIC_TENANT_ID: () => PUBLIC_TENANT_ID,
274
+ ROWND_PLUGIN_ERROR_MESSAGES: () => ROWND_PLUGIN_ERROR_MESSAGES,
275
+ RowndPluginError: () => RowndPluginError,
276
+ default: () => index_default,
277
+ init: () => init
278
+ });
279
+ module.exports = __toCommonJS(index_exports);
280
+
281
+ // ../../shared/js/src/createPluginInit.ts
282
+ var import_supertokens_js_override = __toESM(require_build());
283
+ var createPluginInitFunction = (init2, getImplementation, getNormalisedConfig = (config2) => config2) => {
284
+ const getNormalizedImplementation = typeof getImplementation === "function" ? getImplementation : (_config) => getImplementation || {};
285
+ return (inputConfig) => {
286
+ const config2 = getNormalisedConfig(inputConfig || {});
287
+ const baseImplementation = getNormalizedImplementation(config2);
288
+ const overrideBuilder = new import_supertokens_js_override.OverrideableBuilder(baseImplementation);
289
+ if (inputConfig?.override) {
290
+ overrideBuilder.override(inputConfig.override);
291
+ }
292
+ const actualImplementation = overrideBuilder.build();
293
+ return init2(config2, actualImplementation);
294
+ };
295
+ };
296
+
297
+ // ../../shared/nodejs/src/pluginUserMetadata.ts
298
+ var import_usermetadata = __toESM(require("supertokens-node/recipe/usermetadata"));
299
+
300
+ // ../../shared/nodejs/src/withRequestHandler.ts
301
+ var withRequestHandler = (fn) => {
302
+ return async (req, res, session, userContext) => {
303
+ const result = await fn(req, res, session, userContext);
304
+ if (result.status === "OK") {
305
+ res.setStatusCode(200);
306
+ } else {
307
+ res.setStatusCode(Number(result.code) || 400);
308
+ }
309
+ res.sendJSONResponse(result);
310
+ return null;
311
+ };
312
+ };
313
+
314
+ // ../../shared/nodejs/src/log/logger.ts
315
+ var import_util = __toESM(require("util"));
316
+
317
+ // ../../shared/nodejs/src/log/common.ts
318
+ function setup(env) {
319
+ createDebug.debug = createDebug;
320
+ createDebug.default = createDebug;
321
+ createDebug.coerce = coerce;
322
+ createDebug.disable = disable;
323
+ createDebug.enable = enable;
324
+ createDebug.enabled = enabled;
325
+ createDebug.humanize = env.humanize;
326
+ createDebug.destroy = destroy;
327
+ Object.keys(env).forEach((key) => {
328
+ createDebug[key] = env[key];
329
+ });
330
+ createDebug.names = [];
331
+ createDebug.skips = [];
332
+ createDebug.formatters = {};
333
+ function selectColor(namespace) {
334
+ let hash = 0;
335
+ for (let i = 0; i < namespace.length; i++) {
336
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
337
+ hash |= 0;
338
+ }
339
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
340
+ }
341
+ createDebug.selectColor = selectColor;
342
+ function createDebug(namespace) {
343
+ let prevTime;
344
+ let enableOverride = null;
345
+ let namespacesCache;
346
+ let enabledCache;
347
+ function debug(...args) {
348
+ if (!debug.enabled) {
349
+ return;
350
+ }
351
+ const self = debug;
352
+ const curr = Number(/* @__PURE__ */ new Date());
353
+ const ms = curr - (prevTime || curr);
354
+ self.diff = ms;
355
+ self.prev = prevTime;
356
+ self.curr = curr;
357
+ prevTime = curr;
358
+ args[0] = createDebug.coerce(args[0]);
359
+ if (typeof args[0] !== "string") {
360
+ args.unshift("%O");
361
+ }
362
+ let index = 0;
363
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
364
+ if (match === "%%") {
365
+ return "%";
366
+ }
367
+ index++;
368
+ const formatter = createDebug.formatters[format];
369
+ if (typeof formatter === "function") {
370
+ const val = args[index];
371
+ match = formatter.call(self, val);
372
+ args.splice(index, 1);
373
+ index--;
374
+ }
375
+ return match;
376
+ });
377
+ createDebug.formatArgs.call(self, args);
378
+ const logFn = self.log || createDebug.log;
379
+ logFn.apply(self, args);
380
+ }
381
+ debug.namespace = namespace;
382
+ debug.useColors = createDebug.useColors();
383
+ debug.color = createDebug.selectColor(namespace);
384
+ debug.extend = extend;
385
+ debug.destroy = createDebug.destroy;
386
+ Object.defineProperty(debug, "enabled", {
387
+ enumerable: true,
388
+ configurable: false,
389
+ get: () => {
390
+ if (enableOverride !== null) {
391
+ return enableOverride;
392
+ }
393
+ if (namespacesCache !== createDebug.namespaces) {
394
+ namespacesCache = createDebug.namespaces;
395
+ enabledCache = createDebug.enabled(namespace);
396
+ }
397
+ return enabledCache;
398
+ },
399
+ set: (v) => {
400
+ enableOverride = v;
401
+ }
402
+ });
403
+ if (typeof createDebug.init === "function") {
404
+ createDebug.init(debug);
405
+ }
406
+ return debug;
407
+ }
408
+ function extend(namespace, delimiter) {
409
+ const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
410
+ newDebug.log = this.log;
411
+ return newDebug;
412
+ }
413
+ function enable(namespaces) {
414
+ createDebug.save(namespaces);
415
+ createDebug.namespaces = namespaces;
416
+ createDebug.names = [];
417
+ createDebug.skips = [];
418
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
419
+ for (const ns of split) {
420
+ if (ns[0] === "-") {
421
+ createDebug.skips.push(ns.slice(1));
422
+ } else {
423
+ createDebug.names.push(ns);
424
+ }
425
+ }
426
+ }
427
+ function matchesTemplate(search, template) {
428
+ let searchIndex = 0;
429
+ let templateIndex = 0;
430
+ let starIndex = -1;
431
+ let matchIndex = 0;
432
+ while (searchIndex < search.length) {
433
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
434
+ if (template[templateIndex] === "*") {
435
+ starIndex = templateIndex;
436
+ matchIndex = searchIndex;
437
+ templateIndex++;
438
+ } else {
439
+ searchIndex++;
440
+ templateIndex++;
441
+ }
442
+ } else if (starIndex !== -1) {
443
+ templateIndex = starIndex + 1;
444
+ matchIndex++;
445
+ searchIndex = matchIndex;
446
+ } else {
447
+ return false;
448
+ }
449
+ }
450
+ while (templateIndex < template.length && template[templateIndex] === "*") {
451
+ templateIndex++;
452
+ }
453
+ return templateIndex === template.length;
454
+ }
455
+ function disable() {
456
+ const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace)].join(",");
457
+ createDebug.enable("");
458
+ return namespaces;
459
+ }
460
+ function enabled(name) {
461
+ for (const skip of createDebug.skips) {
462
+ if (matchesTemplate(name, skip)) {
463
+ return false;
464
+ }
465
+ }
466
+ for (const ns of createDebug.names) {
467
+ if (matchesTemplate(name, ns)) {
468
+ return true;
469
+ }
470
+ }
471
+ return false;
472
+ }
473
+ function coerce(val) {
474
+ if (val instanceof Error) {
475
+ return val.stack || val.message;
476
+ }
477
+ return val;
478
+ }
479
+ function destroy() {
480
+ console.warn(
481
+ "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
482
+ );
483
+ }
484
+ createDebug.enable(createDebug.load());
485
+ return createDebug;
486
+ }
487
+ var common_default = setup;
488
+
489
+ // ../../shared/nodejs/src/log/logger.ts
490
+ var BASIC_COLORS = [6, 2, 3, 4, 5, 1];
491
+ var EXTENDED_COLORS = [
492
+ 20,
493
+ 21,
494
+ 26,
495
+ 27,
496
+ 32,
497
+ 33,
498
+ 38,
499
+ 39,
500
+ 40,
501
+ 41,
502
+ 42,
503
+ 43,
504
+ 44,
505
+ 45,
506
+ 56,
507
+ 57,
508
+ 62,
509
+ 63,
510
+ 68,
511
+ 69,
512
+ 74,
513
+ 75,
514
+ 76,
515
+ 77,
516
+ 78,
517
+ 79,
518
+ 80,
519
+ 81,
520
+ 92,
521
+ 93,
522
+ 98,
523
+ 99,
524
+ 112,
525
+ 113,
526
+ 128,
527
+ 129,
528
+ 134,
529
+ 135,
530
+ 148,
531
+ 149,
532
+ 160,
533
+ 161,
534
+ 162,
535
+ 163,
536
+ 164,
537
+ 165,
538
+ 166,
539
+ 167,
540
+ 168,
541
+ 169,
542
+ 170,
543
+ 171,
544
+ 172,
545
+ 173,
546
+ 178,
547
+ 179,
548
+ 184,
549
+ 185,
550
+ 196,
551
+ 197,
552
+ 198,
553
+ 199,
554
+ 200,
555
+ 201,
556
+ 202,
557
+ 203,
558
+ 204,
559
+ 205,
560
+ 206,
561
+ 207,
562
+ 208,
563
+ 209,
564
+ 214,
565
+ 215,
566
+ 220,
567
+ 221
568
+ ];
569
+ function supportsExtendedColors() {
570
+ try {
571
+ const supportsColor = require_supports_color();
572
+ return supportsColor && (supportsColor.stderr || supportsColor).level >= 2;
573
+ } catch {
574
+ return false;
575
+ }
576
+ }
577
+ function shouldUseColors() {
578
+ return false;
579
+ }
580
+ function formatArgs(args) {
581
+ const { namespace, useColors, color } = this;
582
+ if (useColors) {
583
+ const colorCode = color < 8 ? `3${color}` : `38;5;${color}`;
584
+ const prefix = `\x1B[${colorCode};1m${namespace}\x1B[0m`;
585
+ args[0] = `${prefix} ${args[0]}`.split("\n").join(`
586
+ ${prefix} `);
587
+ args.push(`\x1B[${colorCode}m+${humanizeTime(this.diff)}\x1B[0m`);
588
+ } else {
589
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
590
+ args[0] = `${timestamp} ${namespace} ${args[0]}`;
591
+ }
592
+ }
593
+ function writeOutput(...args) {
594
+ process.stderr.write(import_util.default.format(...args) + "\n");
595
+ }
596
+ function saveConfig(namespaces) {
597
+ if (namespaces) {
598
+ process.env.DEBUG = namespaces;
599
+ } else {
600
+ delete process.env.DEBUG;
601
+ }
602
+ }
603
+ function loadConfig() {
604
+ return process.env.DEBUG;
605
+ }
606
+ function humanizeTime(milliseconds) {
607
+ if (milliseconds >= 1e3) {
608
+ const seconds = Math.round(milliseconds / 1e3);
609
+ return `${seconds}s`;
610
+ }
611
+ return `${milliseconds}ms`;
612
+ }
613
+ function createLoggerConfig() {
614
+ const colors = supportsExtendedColors() ? EXTENDED_COLORS : BASIC_COLORS;
615
+ return {
616
+ colors,
617
+ useColors: shouldUseColors,
618
+ formatArgs,
619
+ log: writeOutput,
620
+ save: saveConfig,
621
+ load: loadConfig,
622
+ humanize: humanizeTime
623
+ };
624
+ }
625
+ var config = createLoggerConfig();
626
+ var logger = common_default(config);
627
+ if (logger.formatters) {
628
+ logger.formatters.o = function(value) {
629
+ return import_util.default.inspect(value, { colors: this.useColors, compact: true }).split("\n").map((line) => line.trim()).join(" ");
630
+ };
631
+ logger.formatters.O = function(value) {
632
+ return import_util.default.inspect(value, { colors: this.useColors, compact: false });
633
+ };
634
+ }
635
+ var logger_default = logger;
636
+
637
+ // ../../shared/nodejs/src/log/index.ts
638
+ var log_default = logger_default;
639
+
640
+ // ../../shared/nodejs/src/logger.ts
641
+ var getFileLocation = () => {
642
+ let errorObject = new Error();
643
+ if (errorObject.stack === void 0) {
644
+ return "N/A";
645
+ }
646
+ let errorStack = errorObject.stack.split("\n");
647
+ for (let i = 1; i < errorStack.length; i++) {
648
+ if (!errorStack[i]?.includes("logger.js")) {
649
+ return errorStack[i]?.match(/(?<=\().+?(?=\))/g);
650
+ }
651
+ }
652
+ return "N/A";
653
+ };
654
+ var buildLogger = (pluginId, version, { fileLocation = true } = {}) => {
655
+ const namespace = `com.supertokens.plugin.${pluginId}`;
656
+ function logDebugMessage2(message) {
657
+ if (log_default.enabled(namespace)) {
658
+ log_default(namespace)(
659
+ `{t: "${(/* @__PURE__ */ new Date()).toISOString()}", message: "${message}", file: "${fileLocation ? getFileLocation() : "N/A"}" version: "${version}"}`
660
+ );
661
+ console.log();
662
+ }
663
+ }
664
+ function enableDebugLogs2() {
665
+ log_default.enable(namespace);
666
+ }
667
+ return {
668
+ logDebugMessage: logDebugMessage2,
669
+ enableDebugLogs: enableDebugLogs2
670
+ };
671
+ };
672
+
673
+ // src/plugin.ts
674
+ var import_node = require("@rownd/node");
675
+ var import_supertokens_node = __toESM(require("supertokens-node"));
676
+
677
+ // src/constants.ts
678
+ var PLUGIN_ID = "supertokens-plugin-rownd";
679
+ var PLUGIN_SDK_VERSION = ["23.0.0", "23.0.1", ">=23.0.1"];
680
+ var HANDLE_BASE_PATH = "/plugin/rownd";
681
+ var PUBLIC_TENANT_ID = "public";
682
+
683
+ // src/logger.ts
684
+ var { logDebugMessage, enableDebugLogs } = buildLogger(
685
+ PLUGIN_ID,
686
+ PLUGIN_SDK_VERSION
687
+ );
688
+
689
+ // src/plugin.ts
690
+ var import_session = __toESM(require("supertokens-node/recipe/session"));
691
+
692
+ // src/telemetry/axiomTelemetryClient.ts
693
+ var DEFAULT_AXIOM_URL = "https://api.axiom.co/v1/datasets";
694
+ var AxiomTelemetryClient = class {
695
+ constructor(token, dataset, endpoint) {
696
+ this.token = token;
697
+ this.dataset = dataset;
698
+ const baseUrl = (endpoint ?? DEFAULT_AXIOM_URL).replace(/\/$/, "");
699
+ this.url = `${baseUrl}/${dataset}/ingest`;
700
+ }
701
+ token;
702
+ dataset;
703
+ url;
704
+ async recordEvent(event) {
705
+ await fetch(this.url, {
706
+ method: "POST",
707
+ headers: {
708
+ Authorization: `Bearer ${this.token}`,
709
+ "Content-Type": "application/json"
710
+ },
711
+ body: JSON.stringify([
712
+ {
713
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
714
+ plugin: PLUGIN_ID,
715
+ ...event
716
+ }
717
+ ])
718
+ });
719
+ }
720
+ };
721
+
722
+ // src/telemetry/openTelemetryClient.ts
723
+ var import_api = require("@opentelemetry/api");
724
+ var OpenTelemetryClient = class {
725
+ recordEvent(event) {
726
+ const tracer = import_api.trace.getTracer("supertokens-plugin-rownd", "0.1.0");
727
+ const span = tracer.startSpan("rownd.migrate");
728
+ span.setAttributes({
729
+ "rownd.outcome": event.outcome,
730
+ "rownd.duration_ms": event.durationMs,
731
+ "rownd.tenant_id": event.tenantId ?? "",
732
+ "rownd.rownd_user_id": event.rowndUserId ?? "",
733
+ "rownd.supertokens_user_id": event.superTokensUserId ?? ""
734
+ });
735
+ if (event.outcome === "error") {
736
+ const err = new Error(event.error.message);
737
+ if (event.error.name) {
738
+ err.name = event.error.name;
739
+ }
740
+ span.recordException(err);
741
+ span.setStatus({
742
+ code: import_api.SpanStatusCode.ERROR,
743
+ message: event.error.message
744
+ });
745
+ } else {
746
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
747
+ }
748
+ span.end();
749
+ }
750
+ };
751
+
752
+ // src/telemetry/createTelemetryClient.ts
753
+ function createClient(telemetryConfig) {
754
+ let client;
755
+ if (telemetryConfig?.provider === "opentelemetry") {
756
+ client = new OpenTelemetryClient();
757
+ } else if (telemetryConfig?.provider === "axiom") {
758
+ client = new AxiomTelemetryClient(
759
+ telemetryConfig.token,
760
+ telemetryConfig.dataset,
761
+ telemetryConfig.url
762
+ );
763
+ } else if (telemetryConfig?.provider === "custom") {
764
+ client = telemetryConfig.factory();
765
+ }
766
+ return {
767
+ recordSuccess: (event) => {
768
+ if (!client) {
769
+ return;
770
+ }
771
+ safeRecordEvent(client, event, "success");
772
+ },
773
+ recordError: (input) => {
774
+ if (!client) {
775
+ return;
776
+ }
777
+ const event = {
778
+ outcome: "error",
779
+ durationMs: Date.now() - input.startedAt,
780
+ tenantId: input.tenantId,
781
+ rowndUserId: input.rowndUserId,
782
+ superTokensUserId: input.superTokensUserId,
783
+ error: {
784
+ message: input.error instanceof Error ? input.error.message : "Unknown error",
785
+ name: input.error instanceof Error ? input.error.name : void 0
786
+ }
787
+ };
788
+ safeRecordEvent(client, event, "error");
789
+ }
790
+ };
791
+ }
792
+ function safeRecordEvent(client, event, outcome) {
793
+ try {
794
+ Promise.resolve(client.recordEvent(event)).catch((error) => {
795
+ logDebugMessage(
796
+ `Failed to record telemetry ${outcome} event. Error: ${error instanceof Error ? error.message : "Unknown error"}`
797
+ );
798
+ });
799
+ } catch (error) {
800
+ logDebugMessage(
801
+ `Failed to record telemetry ${outcome} event. Error: ${error instanceof Error ? error.message : "Unknown error"}`
802
+ );
803
+ }
804
+ }
805
+
806
+ // src/errors.ts
807
+ var ROWND_PLUGIN_ERROR_MESSAGES = {
808
+ MISSING_AUTHORIZATION_HEADER: "Missing authorization header",
809
+ INVALID_TOKEN: "Invalid token",
810
+ ROWND_USER_NOT_FOUND: "User not found in Rownd"
811
+ };
812
+ var RowndPluginError = class extends Error {
813
+ constructor(type) {
814
+ super(ROWND_PLUGIN_ERROR_MESSAGES[type]);
815
+ }
816
+ };
817
+
818
+ // src/pluginImplementation.ts
819
+ var rowndClient;
820
+ function setRowndClient(client) {
821
+ rowndClient = client;
822
+ }
823
+ function getRowndClient() {
824
+ if (!rowndClient) {
825
+ throw new Error("Rownd client not initialized");
826
+ }
827
+ return rowndClient;
828
+ }
829
+ async function parseRequest(req) {
830
+ const authHeader = req.getHeaderValue("authorization");
831
+ if (!authHeader) {
832
+ throw new RowndPluginError("MISSING_AUTHORIZATION_HEADER");
833
+ }
834
+ const token = authHeader.replace(/^Bearer /i, "");
835
+ if (!token) {
836
+ throw new RowndPluginError("INVALID_TOKEN");
837
+ }
838
+ return {
839
+ token
840
+ };
841
+ }
842
+ function mapRowndUserToSuperTokens(rowndUser) {
843
+ const loginMethods = [];
844
+ const rowndUserData = rowndUser.data || {};
845
+ const rowndUserVerifiedData = rowndUser.verified_data || {};
846
+ if (!rowndUserData.user_id) {
847
+ throw new Error("Rownd user has no user_id");
848
+ }
849
+ if (rowndUserData.google_id) {
850
+ if (!rowndUserData.email) {
851
+ throw new Error("Rownd Google user is missing email");
852
+ }
853
+ loginMethods.push({
854
+ recipeId: "thirdparty",
855
+ thirdPartyId: "google",
856
+ thirdPartyUserId: rowndUserData.google_id,
857
+ email: rowndUserData.email,
858
+ isVerified: !!rowndUserVerifiedData.google_id
859
+ });
860
+ }
861
+ if (rowndUserData.apple_id) {
862
+ if (!rowndUserData.email) {
863
+ throw new Error("Rownd Apple user is missing email");
864
+ }
865
+ loginMethods.push({
866
+ recipeId: "thirdparty",
867
+ thirdPartyId: "apple",
868
+ thirdPartyUserId: rowndUserData.apple_id,
869
+ email: rowndUserData.email,
870
+ isVerified: !!rowndUserVerifiedData.apple_id
871
+ });
872
+ }
873
+ if (rowndUserData.phone_number) {
874
+ loginMethods.push({
875
+ recipeId: "passwordless",
876
+ phoneNumber: rowndUserData.phone_number,
877
+ isVerified: !!rowndUserVerifiedData.phone_number
878
+ });
879
+ }
880
+ if (rowndUserData.email && loginMethods.length === 0) {
881
+ loginMethods.push({
882
+ recipeId: "passwordless",
883
+ email: rowndUserData.email,
884
+ isVerified: !!rowndUserVerifiedData.email
885
+ });
886
+ }
887
+ if (loginMethods.length === 0) {
888
+ throw new Error("No valid login methods found in Rownd user data");
889
+ }
890
+ const rowndUserMeta = rowndUser.meta || {};
891
+ const rowndUserAttributes = rowndUser.attributes || {};
892
+ const userMetadata = {
893
+ data: {
894
+ ...rowndUserData
895
+ },
896
+ meta: {
897
+ ...rowndUserMeta
898
+ },
899
+ verified_data: {
900
+ ...rowndUserVerifiedData
901
+ },
902
+ attributes: {
903
+ ...rowndUserAttributes
904
+ },
905
+ rownd_migrated: true,
906
+ rownd_user_id: rowndUserData.user_id
907
+ };
908
+ return {
909
+ externalUserId: rowndUserData.user_id,
910
+ loginMethods,
911
+ userMetadata
912
+ };
913
+ }
914
+ async function importUser(stUser, config2) {
915
+ const headers = {
916
+ "Content-Type": "application/json"
917
+ };
918
+ if (config2.apiKey) {
919
+ headers["api-key"] = config2.apiKey;
920
+ }
921
+ const response = await fetch(`${config2.connectionURI}/bulk-import/import`, {
922
+ method: "POST",
923
+ headers,
924
+ body: JSON.stringify(stUser)
925
+ });
926
+ if (!response.ok) {
927
+ const errorText = await response.text();
928
+ throw new Error(
929
+ `Bulk import failed with status ${response.status}: ${errorText}`
930
+ );
931
+ }
932
+ const importResponse = await response.json();
933
+ if (importResponse.status !== "OK" || !importResponse.user) {
934
+ throw new Error(
935
+ `Bulk import failed: ${importResponse.message || "Missing user in response"}`
936
+ );
937
+ }
938
+ return importResponse.user;
939
+ }
940
+ async function validateRowndToken(token) {
941
+ const client = getRowndClient();
942
+ const tokenInfo = await client.validateToken(token);
943
+ return tokenInfo.user_id;
944
+ }
945
+ async function fetchRowndUserInfo(userId) {
946
+ const client = getRowndClient();
947
+ const rowndUser = await client.fetchUserInfo({ user_id: userId });
948
+ if (!rowndUser) {
949
+ throw new RowndPluginError("ROWND_USER_NOT_FOUND");
950
+ }
951
+ return rowndUser;
952
+ }
953
+
954
+ // src/plugin.ts
955
+ var init = createPluginInitFunction(
956
+ (config2) => {
957
+ const rowndClient2 = (0, import_node.createInstance)({
958
+ app_key: config2.rowndAppKey,
959
+ app_secret: config2.rowndAppSecret
960
+ });
961
+ const telemetryClient = createClient(config2.telemetry);
962
+ setRowndClient(rowndClient2);
963
+ if (config2.enableDebugLogs) {
964
+ enableDebugLogs();
965
+ }
966
+ logDebugMessage("Rownd plugin init complete");
967
+ return {
968
+ id: PLUGIN_ID,
969
+ compatibleSDKVersions: PLUGIN_SDK_VERSION,
970
+ init: async () => {
971
+ if (!import_supertokens_node.default.isRecipeInitialized("session")) {
972
+ console.warn(
973
+ "RowndMigrationPlugin: Session recipe is not initialized. Session migration will fail."
974
+ );
975
+ }
976
+ },
977
+ routeHandlers(config3) {
978
+ const apiBasePath = config3.appInfo.apiBasePath.getAsStringDangerous();
979
+ return {
980
+ status: "OK",
981
+ routeHandlers: [
982
+ {
983
+ path: `${apiBasePath}${HANDLE_BASE_PATH}/migrate`,
984
+ method: "post",
985
+ handler: withRequestHandler(
986
+ async (req, res, _session, userContext) => {
987
+ const startedAt = Date.now();
988
+ let tenantId = PUBLIC_TENANT_ID;
989
+ let rowndUserId;
990
+ let superTokensUserId;
991
+ let user;
992
+ let recipeUserId;
993
+ try {
994
+ if (!config3.supertokens) {
995
+ throw new Error("Supertokens config not found");
996
+ }
997
+ const parsed = await parseRequest(req);
998
+ rowndUserId = await validateRowndToken(parsed.token);
999
+ user = await import_supertokens_node.default.getUser(rowndUserId, userContext);
1000
+ if (!user) {
1001
+ const rowndUser = await fetchRowndUserInfo(rowndUserId);
1002
+ const stUserImport = mapRowndUserToSuperTokens(rowndUser);
1003
+ const importedUser = await importUser(
1004
+ stUserImport,
1005
+ config3.supertokens
1006
+ );
1007
+ superTokensUserId = importedUser.id;
1008
+ if (importedUser.loginMethods[0]?.recipeUserId) {
1009
+ recipeUserId = import_supertokens_node.default.convertToRecipeUserId(
1010
+ importedUser.loginMethods[0].recipeUserId
1011
+ );
1012
+ }
1013
+ logDebugMessage(
1014
+ `User migrated successfully. tenantId: ${PUBLIC_TENANT_ID}, rowndUserId: ${rowndUserId}`
1015
+ );
1016
+ } else {
1017
+ superTokensUserId = user.id;
1018
+ recipeUserId = user.loginMethods[0]?.recipeUserId;
1019
+ logDebugMessage(
1020
+ `User already migrated. tenantId: ${PUBLIC_TENANT_ID}, rowndUserId: ${rowndUserId}`
1021
+ );
1022
+ }
1023
+ if (!recipeUserId) {
1024
+ throw new Error("User not found or has no login methods");
1025
+ }
1026
+ await import_session.default.createNewSession(
1027
+ req,
1028
+ res,
1029
+ PUBLIC_TENANT_ID,
1030
+ recipeUserId,
1031
+ {},
1032
+ {},
1033
+ userContext
1034
+ );
1035
+ logDebugMessage(
1036
+ `Session migrated successfully. tenantId: ${PUBLIC_TENANT_ID}, userId: ${superTokensUserId}`
1037
+ );
1038
+ telemetryClient.recordSuccess({
1039
+ outcome: "success",
1040
+ durationMs: Date.now() - startedAt,
1041
+ tenantId,
1042
+ rowndUserId,
1043
+ superTokensUserId
1044
+ });
1045
+ return { status: "OK" };
1046
+ } catch (error) {
1047
+ logDebugMessage(
1048
+ `Migration failed. Error: ${error instanceof Error ? error.message : "Unknown error"}`
1049
+ );
1050
+ telemetryClient.recordError({
1051
+ error,
1052
+ startedAt,
1053
+ tenantId,
1054
+ rowndUserId,
1055
+ superTokensUserId
1056
+ });
1057
+ return {
1058
+ status: "ERROR",
1059
+ message: error instanceof RowndPluginError ? error.message : "Migration failed"
1060
+ };
1061
+ }
1062
+ }
1063
+ )
1064
+ }
1065
+ ]
1066
+ };
1067
+ }
1068
+ };
1069
+ },
1070
+ () => ({}),
1071
+ (config2) => {
1072
+ if (!config2?.rowndAppKey || !config2?.rowndAppSecret) {
1073
+ throw new Error("Missing rowndAppKey or rowndAppSecret in plugin config");
1074
+ }
1075
+ if (config2.telemetry?.provider === "axiom") {
1076
+ if (!config2.telemetry.token || !config2.telemetry.dataset) {
1077
+ throw new Error(
1078
+ "Missing telemetry axiom token or dataset in plugin config"
1079
+ );
1080
+ }
1081
+ }
1082
+ if (config2.telemetry?.provider === "custom") {
1083
+ if (typeof config2.telemetry.factory !== "function") {
1084
+ throw new Error(
1085
+ "Missing telemetry custom factory function in plugin config"
1086
+ );
1087
+ }
1088
+ }
1089
+ return {
1090
+ rowndAppKey: config2.rowndAppKey,
1091
+ rowndAppSecret: config2.rowndAppSecret,
1092
+ enableDebugLogs: config2.enableDebugLogs,
1093
+ telemetry: config2.telemetry
1094
+ };
1095
+ }
1096
+ );
1097
+
1098
+ // src/index.ts
1099
+ var index_default = { init };
1100
+ // Annotate the CommonJS export names for ESM import in node:
1101
+ 0 && (module.exports = {
1102
+ HANDLE_BASE_PATH,
1103
+ PLUGIN_ID,
1104
+ PLUGIN_SDK_VERSION,
1105
+ PUBLIC_TENANT_ID,
1106
+ ROWND_PLUGIN_ERROR_MESSAGES,
1107
+ RowndPluginError,
1108
+ init
1109
+ });