unplugin-dingtalk 1006.0.0 → 1007.0.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.
Files changed (67) hide show
  1. package/dist/{chunk-2YQKM4BX.js → __chrome_devtools-CIQ5zFZx.js} +11 -12
  2. package/dist/__chrome_devtools-CJ3sXpVj.cjs +95 -0
  3. package/dist/__chrome_devtools.cjs +2 -114
  4. package/dist/__chrome_devtools.d.cts +3 -2
  5. package/dist/__chrome_devtools.d.ts +3 -2
  6. package/dist/__chrome_devtools.js +3 -7
  7. package/dist/astro.cjs +12 -676
  8. package/dist/astro.d.cts +7 -10
  9. package/dist/astro.d.ts +8 -10
  10. package/dist/astro.js +12 -17
  11. package/dist/chunk-CUT6urMc.cjs +30 -0
  12. package/dist/esbuild.cjs +9 -667
  13. package/dist/esbuild.d.cts +5 -8
  14. package/dist/esbuild.d.ts +6 -8
  15. package/dist/esbuild.js +8 -10
  16. package/dist/index.cjs +10 -676
  17. package/dist/index.d.cts +11 -13
  18. package/dist/index.d.ts +11 -13
  19. package/dist/index.js +5 -16
  20. package/dist/inject-script.cjs +15 -0
  21. package/dist/inject-script.d.cts +3 -0
  22. package/dist/inject-script.d.ts +4 -0
  23. package/dist/inject-script.js +14 -0
  24. package/dist/main-BvTybYko.js +99 -0
  25. package/dist/main-DQgEHuwp.cjs +101 -0
  26. package/dist/nuxt.cjs +459 -825
  27. package/dist/nuxt.d.cts +7 -10
  28. package/dist/nuxt.d.ts +7 -10
  29. package/dist/nuxt.js +474 -24
  30. package/dist/rollup.cjs +9 -667
  31. package/dist/rollup.d.cts +5 -8
  32. package/dist/rollup.d.ts +6 -8
  33. package/dist/rollup.js +8 -10
  34. package/dist/rspack.cjs +54 -728
  35. package/dist/rspack.d.cts +5 -8
  36. package/dist/rspack.d.ts +6 -8
  37. package/dist/rspack.js +50 -74
  38. package/dist/src-BVX_Roo9.js +364 -0
  39. package/dist/src-hLDO4Q22.cjs +394 -0
  40. package/dist/types-D6mfGNG_.d.ts +38 -0
  41. package/dist/types-DodDHiEA.d.cts +38 -0
  42. package/dist/types.cjs +0 -19
  43. package/dist/types.d.cts +2 -38
  44. package/dist/types.d.ts +2 -38
  45. package/dist/types.js +1 -0
  46. package/dist/utils-Chlbb6jf.js +23 -0
  47. package/dist/utils-CmfBxo4J.cjs +41 -0
  48. package/dist/utils.cjs +4 -33
  49. package/dist/utils.d.cts +6 -3
  50. package/dist/utils.d.ts +6 -3
  51. package/dist/utils.js +3 -7
  52. package/dist/vite-CKIDsKJ-.cjs +24 -0
  53. package/dist/vite-DoBUfGyY.js +18 -0
  54. package/dist/vite.cjs +5 -824
  55. package/dist/vite.d.cts +4 -7
  56. package/dist/vite.d.ts +5 -7
  57. package/dist/vite.js +6 -10
  58. package/dist/webpack.cjs +52 -722
  59. package/dist/webpack.d.cts +5 -8
  60. package/dist/webpack.d.ts +6 -8
  61. package/dist/webpack.js +48 -68
  62. package/package.json +12 -10
  63. package/dist/chunk-5JBD5THX.js +0 -20
  64. package/dist/chunk-EG2ZYJ3S.js +0 -542
  65. package/dist/chunk-KQOHODTC.js +0 -9
  66. package/dist/chunk-LMNMIIAV.js +0 -26
  67. package/dist/main-Q4R5NCQC.js +0 -129
package/dist/nuxt.cjs CHANGED
@@ -1,844 +1,478 @@
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 __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __esm = (fn, res) => function __init() {
23
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
24
- };
25
- var __export = (target, all) => {
26
- for (var name in all)
27
- __defProp(target, name, { get: all[name], enumerable: true });
28
- };
29
- var __copyProps = (to, from, except, desc) => {
30
- if (from && typeof from === "object" || typeof from === "function") {
31
- for (let key of __getOwnPropNames(from))
32
- if (!__hasOwnProp.call(to, key) && key !== except)
33
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
- }
35
- return to;
36
- };
37
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
- // If the importer is in node compatibility mode or this is not an ESM
39
- // file that has been converted to a CommonJS file using a Babel-
40
- // compatible transform (i.e. "__esModule" has not been set), then set
41
- // "default" to the CommonJS "module.exports" for node compatibility.
42
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
- mod
44
- ));
45
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
-
47
- // node_modules/.pnpm/vite-plugin-vconsole@2.1.1/node_modules/vite-plugin-vconsole/dist/main.mjs
48
- var main_exports = {};
49
- __export(main_exports, {
50
- default: () => main_default,
51
- viteVConsole: () => viteVConsole
52
- });
53
- function viteVConsole(opt) {
54
- const {
55
- entry,
56
- enabled = true,
57
- config: config2 = {},
58
- plugin,
59
- customHide = false,
60
- dynamicConfig = {},
61
- eventListener = ""
62
- } = opt;
63
- let entryPath = Array.isArray(entry) ? entry : [entry];
64
- if (process.platform === "win32")
65
- entryPath = entryPath.map((item) => item.replace(/\\/g, "/"));
66
- const enabledTruly = enabled;
67
- return {
68
- name: "vite:vconsole",
69
- enforce: "pre",
70
- transform(_source, id) {
71
- if (entryPath.includes(id) && enabledTruly) {
72
- const code = `/* eslint-disable */;
73
- import VConsole from 'vconsole';
74
- // config
75
- const vConsole = new VConsole({${parseVConsoleOptions(
76
- config2
77
- )}});
78
- window.vConsole = vConsole;
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ require('./__chrome_devtools-CJ3sXpVj.cjs');
3
+ const require_src = require('./src-hLDO4Q22.cjs');
4
+ const require_utils = require('./utils-CmfBxo4J.cjs');
5
+ const require_vite = require('./vite-CKIDsKJ-.cjs');
6
+ const http_proxy = require_chunk.__toESM(require("http-proxy"));
7
+ const picocolors = require_chunk.__toESM(require("picocolors"));
8
+ const __nuxt_kit = require_chunk.__toESM(require("@nuxt/kit"));
9
+ require("@nuxt/schema");
79
10
 
80
- // plugins
81
- ${getPlugins(plugin)}
82
-
83
- // dynamic config
84
- window.vConsole.dynamicFunction = function() {
85
- if (${getDynamicConfig(dynamicConfig).length > 0}) {
86
- vConsole.setOption({${getDynamicConfig(dynamicConfig)}});
87
- }
88
- };
89
-
90
- window.vConsole.dynamicChange = {
91
- value: new Date().getTime()
92
- };
93
-
94
- window.vConsole.dynamicFunction();
95
-
96
- if (${customHide}) {
97
- vConsole.hideSwitch();
98
- }
99
-
100
- // In order to be compatible with old equipment, I used defineProperty. In the future, when proxy covers enough devices, proxy will be used.
101
- Object.defineProperty(window.vConsole.dynamicChange, 'value', {
102
- get: function() {
103
- return this._value;
104
- },
105
- set: function(newValue) {
106
- window.vConsole.dynamicFunction();
107
- this._value = newValue;
108
- }
109
- });
110
-
111
- // eventListener
112
- ${eventListener}
113
- /* eslint-enable */${_source}`;
114
- return {
115
- code,
116
- map: null
117
- // support source map
118
- };
119
- }
120
- return {
121
- code: _source,
122
- map: null
123
- // support source map
124
- };
125
- }
126
- };
11
+ //#region node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
12
+ function isPlainObject(value) {
13
+ if (value === null || typeof value !== "object") return false;
14
+ const prototype = Object.getPrototypeOf(value);
15
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
16
+ if (Symbol.iterator in value) return false;
17
+ if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
18
+ return true;
19
+ }
20
+ function _defu(baseObject, defaults, namespace = ".", merger) {
21
+ if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
22
+ const object = Object.assign({}, defaults);
23
+ for (const key in baseObject) {
24
+ if (key === "__proto__" || key === "constructor") continue;
25
+ const value = baseObject[key];
26
+ if (value === null || value === void 0) continue;
27
+ if (merger && merger(object, key, value, namespace)) continue;
28
+ if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
29
+ else if (isPlainObject(value) && isPlainObject(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
30
+ else object[key] = value;
31
+ }
32
+ return object;
127
33
  }
128
- var parseVConsoleOptions, getEventItems, getDynamicConfig, getPlugins, main_default;
129
- var init_main = __esm({
130
- "node_modules/.pnpm/vite-plugin-vconsole@2.1.1/node_modules/vite-plugin-vconsole/dist/main.mjs"() {
131
- "use strict";
132
- parseVConsoleOptions = (config2) => Object.keys(config2).reduce((code, key) => {
133
- const value = config2[key];
134
- if (typeof value === "function") {
135
- if (/^[(f]/.test(value.toString())) {
136
- code += `${key}: ${value},`;
137
- return code;
138
- } else {
139
- code += `${value},`;
140
- return code;
141
- }
142
- }
143
- code += `${key}: ${JSON.stringify(config2[key])},`;
144
- return code;
145
- }, "");
146
- getEventItems = (event, id) => {
147
- return event.map(
148
- (ele) => `
149
- ${id}.on('${ele.eventName}', ${ele.callback})
150
- `
151
- ).join(";");
152
- };
153
- getDynamicConfig = (dynamicConfig) => {
154
- let configString = "";
155
- if (!dynamicConfig) {
156
- return configString;
157
- }
158
- for (const key in dynamicConfig) {
159
- if (typeof dynamicConfig[key] === "string") {
160
- configString += `${key}: ${dynamicConfig[key]},`;
161
- }
162
- }
163
- return configString;
164
- };
165
- getPlugins = (plugin) => {
166
- let plugins = "";
167
- if (plugin && plugin.length) {
168
- plugins = plugin.map(
169
- (e) => `
170
- const ${e.id} = new VConsole.VConsolePlugin('${e.id}', '${e.name}');
171
- ${getEventItems(e.event, e.id)}
172
- vConsole.addPlugin(${e.id})
173
- `
174
- ).join(";");
175
- }
176
- return plugins;
177
- };
178
- main_default = viteVConsole;
179
- }
34
+ function createDefu(merger) {
35
+ return (...arguments_) => arguments_.reduce((p, c$1) => _defu(p, c$1, "", merger), {});
36
+ }
37
+ const defu = createDefu();
38
+ const defuFn = createDefu((object, key, currentValue) => {
39
+ if (object[key] !== void 0 && typeof currentValue === "function") {
40
+ object[key] = currentValue(object[key]);
41
+ return true;
42
+ }
180
43
  });
181
-
182
- // src/nuxt.ts
183
- var nuxt_exports = {};
184
- __export(nuxt_exports, {
185
- default: () => nuxt_default
44
+ const defuArrayFn = createDefu((object, key, currentValue) => {
45
+ if (Array.isArray(object[key]) && typeof currentValue === "function") {
46
+ object[key] = currentValue(object[key]);
47
+ return true;
48
+ }
186
49
  });
187
- module.exports = __toCommonJS(nuxt_exports);
188
- var import_kit = require("@nuxt/kit");
189
-
190
- // src/vite.ts
191
- var import_unplugin2 = require("unplugin");
192
50
 
193
- // src/utils.ts
194
- async function interopDefault(m) {
195
- const resolved = await m;
196
- return resolved.default || resolved;
51
+ //#endregion
52
+ //#region node_modules/.pnpm/h3@1.15.4/node_modules/h3/dist/index.mjs
53
+ function hasProp(obj, prop) {
54
+ try {
55
+ return prop in obj;
56
+ } catch {
57
+ return false;
58
+ }
197
59
  }
198
-
199
- // src/index.ts
200
- var import_node_process = __toESM(require("process"), 1);
201
- var import_node_http = require("http");
202
- var import_node_net2 = require("net");
203
- var import_unplugin = require("unplugin");
204
- var import_picocolors = __toESM(require("picocolors"), 1);
205
- var import_cookie = __toESM(require("cookie"), 1);
206
- var import_z_chii = require("z-chii");
207
-
208
- // node_modules/.pnpm/get-port-please@3.1.2/node_modules/get-port-please/dist/index.mjs
209
- var import_node_net = require("net");
210
- var import_node_os = require("os");
211
- var unsafePorts = /* @__PURE__ */ new Set([
212
- 1,
213
- // tcpmux
214
- 7,
215
- // echo
216
- 9,
217
- // discard
218
- 11,
219
- // systat
220
- 13,
221
- // daytime
222
- 15,
223
- // netstat
224
- 17,
225
- // qotd
226
- 19,
227
- // chargen
228
- 20,
229
- // ftp data
230
- 21,
231
- // ftp access
232
- 22,
233
- // ssh
234
- 23,
235
- // telnet
236
- 25,
237
- // smtp
238
- 37,
239
- // time
240
- 42,
241
- // name
242
- 43,
243
- // nicname
244
- 53,
245
- // domain
246
- 69,
247
- // tftp
248
- 77,
249
- // priv-rjs
250
- 79,
251
- // finger
252
- 87,
253
- // ttylink
254
- 95,
255
- // supdup
256
- 101,
257
- // hostriame
258
- 102,
259
- // iso-tsap
260
- 103,
261
- // gppitnp
262
- 104,
263
- // acr-nema
264
- 109,
265
- // pop2
266
- 110,
267
- // pop3
268
- 111,
269
- // sunrpc
270
- 113,
271
- // auth
272
- 115,
273
- // sftp
274
- 117,
275
- // uucp-path
276
- 119,
277
- // nntp
278
- 123,
279
- // NTP
280
- 135,
281
- // loc-srv /epmap
282
- 137,
283
- // netbios
284
- 139,
285
- // netbios
286
- 143,
287
- // imap2
288
- 161,
289
- // snmp
290
- 179,
291
- // BGP
292
- 389,
293
- // ldap
294
- 427,
295
- // SLP (Also used by Apple Filing Protocol)
296
- 465,
297
- // smtp+ssl
298
- 512,
299
- // print / exec
300
- 513,
301
- // login
302
- 514,
303
- // shell
304
- 515,
305
- // printer
306
- 526,
307
- // tempo
308
- 530,
309
- // courier
310
- 531,
311
- // chat
312
- 532,
313
- // netnews
314
- 540,
315
- // uucp
316
- 548,
317
- // AFP (Apple Filing Protocol)
318
- 554,
319
- // rtsp
320
- 556,
321
- // remotefs
322
- 563,
323
- // nntp+ssl
324
- 587,
325
- // smtp (rfc6409)
326
- 601,
327
- // syslog-conn (rfc3195)
328
- 636,
329
- // ldap+ssl
330
- 989,
331
- // ftps-data
332
- 990,
333
- // ftps
334
- 993,
335
- // ldap+ssl
336
- 995,
337
- // pop3+ssl
338
- 1719,
339
- // h323gatestat
340
- 1720,
341
- // h323hostcall
342
- 1723,
343
- // pptp
344
- 2049,
345
- // nfs
346
- 3659,
347
- // apple-sasl / PasswordServer
348
- 4045,
349
- // lockd
350
- 5060,
351
- // sip
352
- 5061,
353
- // sips
354
- 6e3,
355
- // X11
356
- 6566,
357
- // sane-port
358
- 6665,
359
- // Alternate IRC [Apple addition]
360
- 6666,
361
- // Alternate IRC [Apple addition]
362
- 6667,
363
- // Standard IRC [Apple addition]
364
- 6668,
365
- // Alternate IRC [Apple addition]
366
- 6669,
367
- // Alternate IRC [Apple addition]
368
- 6697,
369
- // IRC + TLS
370
- 10080
371
- // Amanda
372
- ]);
373
- function isUnsafePort(port) {
374
- return unsafePorts.has(port);
60
+ var H3Error = class extends Error {
61
+ static __h3_error__ = true;
62
+ statusCode = 500;
63
+ fatal = false;
64
+ unhandled = false;
65
+ statusMessage;
66
+ data;
67
+ cause;
68
+ constructor(message, opts = {}) {
69
+ super(message, opts);
70
+ if (opts.cause && !this.cause) this.cause = opts.cause;
71
+ }
72
+ toJSON() {
73
+ const obj = {
74
+ message: this.message,
75
+ statusCode: sanitizeStatusCode(this.statusCode, 500)
76
+ };
77
+ if (this.statusMessage) obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
78
+ if (this.data !== void 0) obj.data = this.data;
79
+ return obj;
80
+ }
81
+ };
82
+ function createError(input) {
83
+ if (typeof input === "string") return new H3Error(input);
84
+ if (isError(input)) return input;
85
+ const err = new H3Error(input.message ?? input.statusMessage ?? "", { cause: input.cause || input });
86
+ if (hasProp(input, "stack")) try {
87
+ Object.defineProperty(err, "stack", { get() {
88
+ return input.stack;
89
+ } });
90
+ } catch {
91
+ try {
92
+ err.stack = input.stack;
93
+ } catch {}
94
+ }
95
+ if (input.data) err.data = input.data;
96
+ if (input.statusCode) err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
97
+ else if (input.status) err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
98
+ if (input.statusMessage) err.statusMessage = input.statusMessage;
99
+ else if (input.statusText) err.statusMessage = input.statusText;
100
+ if (err.statusMessage) {
101
+ const originalMessage = err.statusMessage;
102
+ const sanitizedMessage = sanitizeStatusMessage(err.statusMessage);
103
+ if (sanitizedMessage !== originalMessage) console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.");
104
+ }
105
+ if (input.fatal !== void 0) err.fatal = input.fatal;
106
+ if (input.unhandled !== void 0) err.unhandled = input.unhandled;
107
+ return err;
375
108
  }
376
- function isSafePort(port) {
377
- return !isUnsafePort(port);
109
+ function isError(input) {
110
+ return input?.constructor?.__h3_error__ === true;
378
111
  }
379
- var __defProp2 = Object.defineProperty;
380
- var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
381
- var __publicField = (obj, key, value) => {
382
- __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
383
- return value;
384
- };
385
- var GetPortError = class extends Error {
386
- constructor(message, opts) {
387
- super(message, opts);
388
- this.message = message;
389
- __publicField(this, "name", "GetPortError");
390
- }
391
- };
392
- function _log(verbose, message) {
393
- if (verbose) {
394
- console.log(`[get-port] ${message}`);
395
- }
112
+ function isMethod(event, expected, allowHead) {
113
+ if (allowHead && event.method === "HEAD") return true;
114
+ if (typeof expected === "string") {
115
+ if (event.method === expected) return true;
116
+ } else if (expected.includes(event.method)) return true;
117
+ return false;
396
118
  }
397
- function _tryPort(port, host) {
398
- return new Promise((resolve) => {
399
- const server = (0, import_node_net.createServer)();
400
- server.unref();
401
- server.on("error", () => {
402
- resolve(false);
403
- });
404
- server.listen({ port, host }, () => {
405
- const { port: port2 } = server.address();
406
- server.close(() => {
407
- resolve(isSafePort(port2) && port2);
408
- });
409
- });
410
- });
119
+ function assertMethod(event, expected, allowHead) {
120
+ if (!isMethod(event, expected, allowHead)) throw createError({
121
+ statusCode: 405,
122
+ statusMessage: "HTTP method is not allowed."
123
+ });
411
124
  }
412
- function _getLocalHosts(additional) {
413
- const hosts = new Set(additional);
414
- for (const _interface of Object.values((0, import_node_os.networkInterfaces)())) {
415
- for (const config2 of _interface || []) {
416
- if (config2.address && !config2.internal && !config2.address.startsWith("fe80::")) {
417
- hosts.add(config2.address);
418
- }
419
- }
420
- }
421
- return [...hosts];
125
+ function getRequestHeaders(event) {
126
+ const _headers = {};
127
+ for (const key in event.node.req.headers) {
128
+ const val = event.node.req.headers[key];
129
+ _headers[key] = Array.isArray(val) ? val.filter(Boolean).join(", ") : val;
130
+ }
131
+ return _headers;
422
132
  }
423
- function _fmtOnHost(hostname) {
424
- return hostname ? `on host ${JSON.stringify(hostname)}` : "on any host";
133
+ const RawBodySymbol = Symbol.for("h3RawBody");
134
+ const ParsedBodySymbol = Symbol.for("h3ParsedBody");
135
+ const PayloadMethods$1 = [
136
+ "PATCH",
137
+ "POST",
138
+ "PUT",
139
+ "DELETE"
140
+ ];
141
+ function readRawBody(event, encoding = "utf8") {
142
+ assertMethod(event, PayloadMethods$1);
143
+ const _rawBody = event._requestBody || event.web?.request?.body || event.node.req[RawBodySymbol] || event.node.req.rawBody || event.node.req.body;
144
+ if (_rawBody) {
145
+ const promise2 = Promise.resolve(_rawBody).then((_resolved) => {
146
+ if (Buffer.isBuffer(_resolved)) return _resolved;
147
+ if (typeof _resolved.pipeTo === "function") return new Promise((resolve, reject) => {
148
+ const chunks = [];
149
+ _resolved.pipeTo(new WritableStream({
150
+ write(chunk) {
151
+ chunks.push(chunk);
152
+ },
153
+ close() {
154
+ resolve(Buffer.concat(chunks));
155
+ },
156
+ abort(reason) {
157
+ reject(reason);
158
+ }
159
+ })).catch(reject);
160
+ });
161
+ else if (typeof _resolved.pipe === "function") return new Promise((resolve, reject) => {
162
+ const chunks = [];
163
+ _resolved.on("data", (chunk) => {
164
+ chunks.push(chunk);
165
+ }).on("end", () => {
166
+ resolve(Buffer.concat(chunks));
167
+ }).on("error", reject);
168
+ });
169
+ if (_resolved.constructor === Object) return Buffer.from(JSON.stringify(_resolved));
170
+ if (_resolved instanceof URLSearchParams) return Buffer.from(_resolved.toString());
171
+ if (_resolved instanceof FormData) return new Response(_resolved).bytes().then((uint8arr) => Buffer.from(uint8arr));
172
+ return Buffer.from(_resolved);
173
+ });
174
+ return encoding ? promise2.then((buff) => buff.toString(encoding)) : promise2;
175
+ }
176
+ if (!Number.parseInt(event.node.req.headers["content-length"] || "") && !String(event.node.req.headers["transfer-encoding"] ?? "").split(",").map((e) => e.trim()).filter(Boolean).includes("chunked")) return Promise.resolve(void 0);
177
+ const promise = event.node.req[RawBodySymbol] = new Promise((resolve, reject) => {
178
+ const bodyData = [];
179
+ event.node.req.on("error", (err) => {
180
+ reject(err);
181
+ }).on("data", (chunk) => {
182
+ bodyData.push(chunk);
183
+ }).on("end", () => {
184
+ resolve(Buffer.concat(bodyData));
185
+ });
186
+ });
187
+ const result = encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
188
+ return result;
425
189
  }
426
- var HOSTNAME_RE = new RegExp("^(?!-)[\\d.:A-Za-z-]{1,63}(?<!-)$");
427
- async function getRandomPort(host) {
428
- const port = await checkPort(0, host);
429
- if (port === false) {
430
- throw new GetPortError(`Unable to find a random port ${_fmtOnHost(host)}`);
431
- }
432
- return port;
190
+ function getRequestWebStream(event) {
191
+ if (!PayloadMethods$1.includes(event.method)) return;
192
+ const bodyStream = event.web?.request?.body || event._requestBody;
193
+ if (bodyStream) return bodyStream;
194
+ const _hasRawBody = RawBodySymbol in event.node.req || "rawBody" in event.node.req || "body" in event.node.req || "__unenv__" in event.node.req;
195
+ if (_hasRawBody) return new ReadableStream({ async start(controller) {
196
+ const _rawBody = await readRawBody(event, false);
197
+ if (_rawBody) controller.enqueue(_rawBody);
198
+ controller.close();
199
+ } });
200
+ return new ReadableStream({ start: (controller) => {
201
+ event.node.req.on("data", (chunk) => {
202
+ controller.enqueue(chunk);
203
+ });
204
+ event.node.req.on("end", () => {
205
+ controller.close();
206
+ });
207
+ event.node.req.on("error", (err) => {
208
+ controller.error(err);
209
+ });
210
+ } });
433
211
  }
434
- async function checkPort(port, host = process.env.HOST, verbose) {
435
- if (!host) {
436
- host = _getLocalHosts([void 0, "0.0.0.0"]);
437
- }
438
- if (!Array.isArray(host)) {
439
- return _tryPort(port, host);
440
- }
441
- for (const _host of host) {
442
- const _port = await _tryPort(port, _host);
443
- if (_port === false) {
444
- if (port < 1024 && verbose) {
445
- _log(
446
- verbose,
447
- `Unable to listen to the privileged port ${port} ${_fmtOnHost(
448
- _host
449
- )}`
450
- );
451
- }
452
- return false;
453
- }
454
- if (port === 0 && _port !== 0) {
455
- port = _port;
456
- }
457
- }
458
- return port;
212
+ const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
213
+ function sanitizeStatusMessage(statusMessage = "") {
214
+ return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
459
215
  }
460
-
461
- // src/index.ts
462
- var import_http_proxy = __toESM(require("http-proxy"), 1);
463
-
464
- // src/__chrome_devtools.ts
465
- function getChromeDevtoolsHtml(targetPort) {
466
- return `<!DOCTYPE html>
467
- <html>
468
-
469
- <head>
470
- <meta charset="utf-8">
471
- <title>DevTools Targets</title>
472
- <style>
473
- body {
474
- font-family: sans-serif;
475
- padding: 2em;
476
- }
477
-
478
- ul {
479
- padding: 0;
480
- }
481
-
482
- li {
483
- margin-bottom: 1.2em;
484
- list-style: none;
485
- line-height: 1.5;
486
- }
487
-
488
- a.button {
489
- display: inline-block;
490
- background: #409eff;
491
- color: #fff;
492
- padding: 0.2em 0.5em;
493
- text-decoration: none;
494
- border-radius: 4px;
495
- margin-top: 0.5em;
496
- font-size: 14px;
497
- }
498
-
499
- a.button:hover {
500
- background: #66b1ff;
501
- }
502
-
503
- #refresh {
504
- margin-bottom: 1.5em;
505
- }
506
- </style>
507
- </head>
508
-
509
- <body>
510
- <h2>\u53EF\u7528 DevTools Targets</h2><button id="refresh">\u5237\u65B0</button>
511
- <ul id="target-list">
512
- <li>\u52A0\u8F7D\u4E2D...</li>
513
- </ul>
514
- <script>
515
- async function fetchTargets() {
516
- const list = document.getElementById("target-list");
517
- list.innerHTML = "<li>\u52A0\u8F7D\u4E2D...</li>";
518
- try {
519
- const resp = await fetch("/__chii_proxy/targets");
520
- const data = await resp.json();
521
- const targets = data.targets || [];
522
- if (targets.length === 0) {
523
- list.innerHTML = "<li>\u6682\u65E0\u53EF\u7528\u7684\u8C03\u8BD5\u76EE\u6807\u3002</li>";
524
- } else {
525
- list.innerHTML = "";
526
- for (const target of targets) {
527
- console.log(target)
528
- const devToolsUrl = "http://localhost:${targetPort}/front_end/chii_app.html?ws=localhost:${targetPort}/client/" + Math.random().toString(20).substring(2, 8) + "?target=" + encodeURIComponent(target.id) + "&rtc=false";
529
- const item = document.createElement("li");
530
- item.innerHTML =
531
- "<div><strong>" + (target.title) + "</strong></div>" +
532
- "<div>URL: " + (target.url || "") + "</div>" +
533
- "<div>UA: <code>" + (target.userAgent || "unknown") + "</code></div>" +
534
- "<a href='" + devToolsUrl + "' target='_blank' class='button'>\u6253\u5F00\u8C03\u8BD5</a>";
535
- list.appendChild(item);
536
- }
537
- }
538
- } catch (e) {
539
- list.innerHTML = "<li>\u83B7\u53D6\u8C03\u8BD5\u76EE\u6807\u5931\u8D25</li>";
540
- }
541
- }
542
- document.getElementById("refresh").onclick = () => window.location.reload();
543
- window.onload = fetchTargets;
544
- document.addEventListener('visibilitychange', window.location.reload);
545
- </script>
546
- </body>
547
-
548
- </html>`;
216
+ function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
217
+ if (!statusCode) return defaultStatusCode;
218
+ if (typeof statusCode === "string") statusCode = Number.parseInt(statusCode, 10);
219
+ if (statusCode < 100 || statusCode > 999) return defaultStatusCode;
220
+ return statusCode;
549
221
  }
550
-
551
- // src/index.ts
552
- var cwd = import_node_process.default.cwd();
553
- var config;
554
- var colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
555
- var resovedInfo = {
556
- availablePort: void 0,
557
- targetURL: void 0
558
- };
559
- function createProxyMiddleware(debug) {
560
- let proxy = null;
561
- const handleUpgrade = (req, socket, head) => {
562
- var _a;
563
- if (proxy && ((_a = req.url) == null ? void 0 : _a.startsWith("/__chii_proxy"))) {
564
- debug("WS upgrade:", req.url);
565
- req.url = req.url.replace("/__chii_proxy", "");
566
- proxy.ws(req, socket, head);
567
- }
568
- };
569
- return (resolvedInfo) => {
570
- return (req, res, next) => {
571
- var _a;
572
- if (!proxy && resolvedInfo.availablePort) {
573
- proxy = import_http_proxy.default.createProxyServer({
574
- target: `http://localhost:${resolvedInfo.availablePort}`,
575
- ws: true
576
- });
577
- proxy.on("error", (err, req2, res2) => {
578
- console.error("Proxy error:", err);
579
- if (res2 instanceof import_node_http.ServerResponse) {
580
- if (!res2.headersSent) {
581
- res2.writeHead(500, { "Content-Type": "text/plain" });
582
- }
583
- res2.end(`Proxy error: ${err.message}`);
584
- } else if (res2 instanceof import_node_net2.Socket) {
585
- res2.destroy();
586
- }
587
- });
588
- if (req.socket.server) {
589
- req.socket.server.on("upgrade", handleUpgrade);
590
- }
591
- }
592
- if (proxy && ((_a = req.url) == null ? void 0 : _a.startsWith("/__chii_proxy"))) {
593
- debug(req.url);
594
- req.url = req.url.replace("/__chii_proxy", "");
595
- proxy.web(req, res);
596
- } else {
597
- next();
598
- }
599
- };
600
- };
222
+ function splitCookiesString(cookiesString) {
223
+ if (Array.isArray(cookiesString)) return cookiesString.flatMap((c$1) => splitCookiesString(c$1));
224
+ if (typeof cookiesString !== "string") return [];
225
+ const cookiesStrings = [];
226
+ let pos = 0;
227
+ let start;
228
+ let ch;
229
+ let lastComma;
230
+ let nextStart;
231
+ let cookiesSeparatorFound;
232
+ const skipWhitespace = () => {
233
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) pos += 1;
234
+ return pos < cookiesString.length;
235
+ };
236
+ const notSpecialChar = () => {
237
+ ch = cookiesString.charAt(pos);
238
+ return ch !== "=" && ch !== ";" && ch !== ",";
239
+ };
240
+ while (pos < cookiesString.length) {
241
+ start = pos;
242
+ cookiesSeparatorFound = false;
243
+ while (skipWhitespace()) {
244
+ ch = cookiesString.charAt(pos);
245
+ if (ch === ",") {
246
+ lastComma = pos;
247
+ pos += 1;
248
+ skipWhitespace();
249
+ nextStart = pos;
250
+ while (pos < cookiesString.length && notSpecialChar()) pos += 1;
251
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
252
+ cookiesSeparatorFound = true;
253
+ pos = nextStart;
254
+ cookiesStrings.push(cookiesString.slice(start, lastComma));
255
+ start = pos;
256
+ } else pos = lastComma + 1;
257
+ } else pos += 1;
258
+ }
259
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start));
260
+ }
261
+ return cookiesStrings;
601
262
  }
602
- var unpluginFactory = (options) => {
603
- const {
604
- chii
605
- } = options || {};
606
- const enableChii = (chii == null ? void 0 : chii.enable) !== false;
607
- function debug(...args) {
608
- if (options == null ? void 0 : options.debug) {
609
- console.log(` ${import_picocolors.default.yellow("DEBUG")} `, ...args);
610
- }
611
- }
612
- const unpluginDing = {
613
- name: "unplugin-dingtalk",
614
- enforce: "pre",
615
- resolveId(source) {
616
- if (source === "chii-client") {
617
- return source;
618
- }
619
- },
620
- loadInclude(id) {
621
- return id === "chii-client";
622
- },
623
- load(id) {
624
- var _a, _b;
625
- if (id === "chii-client") {
626
- return `
627
- ;(function(){
628
- if (document.getElementById('__chii_client')) return;
629
- const script = document.createElement('script');
630
- script.id = '__chii_client';
631
- script.src="/__chii_proxy/target.js";
632
- ${((_a = options == null ? void 0 : options.chii) == null ? void 0 : _a.embedded) ? "script.setAttribute('embedded','true');" : ""}
633
- document.body.appendChild(script);
634
- })();
635
- if (import.meta.hot) {
636
- import.meta.hot.accept(() => {
637
- const old = document.getElementById('__chii_client');
638
- if (old) old.remove();
639
- const script = document.createElement('script');
640
- script.id = '__chii_client';
641
- script.src="/__chii_proxy/target.js";
642
- ${((_b = options == null ? void 0 : options.chii) == null ? void 0 : _b.embedded) ? "script.setAttribute('embedded','true');" : ""}
643
- document.body.appendChild(script);
644
- });
263
+ const PayloadMethods = /* @__PURE__ */ new Set([
264
+ "PATCH",
265
+ "POST",
266
+ "PUT",
267
+ "DELETE"
268
+ ]);
269
+ const ignoredHeaders = /* @__PURE__ */ new Set([
270
+ "transfer-encoding",
271
+ "accept-encoding",
272
+ "connection",
273
+ "keep-alive",
274
+ "upgrade",
275
+ "expect",
276
+ "host",
277
+ "accept"
278
+ ]);
279
+ async function proxyRequest(event, target, opts = {}) {
280
+ let body;
281
+ let duplex;
282
+ if (PayloadMethods.has(event.method)) if (opts.streamRequest) {
283
+ body = getRequestWebStream(event);
284
+ duplex = "half";
285
+ } else body = await readRawBody(event, false).catch(() => void 0);
286
+ const method = opts.fetchOptions?.method || event.method;
287
+ const fetchHeaders = mergeHeaders(getProxyRequestHeaders(event, { host: target.startsWith("/") }), opts.fetchOptions?.headers, opts.headers);
288
+ return sendProxy(event, target, {
289
+ ...opts,
290
+ fetchOptions: {
291
+ method,
292
+ body,
293
+ duplex,
294
+ ...opts.fetchOptions,
295
+ headers: fetchHeaders
296
+ }
297
+ });
645
298
  }
646
- `;
647
- }
648
- },
649
- transformInclude(id) {
650
- return !!id.split("?")[0].match(/\.[t|j]s$/);
651
- },
652
- async transform(source, id) {
653
- if ((options == null ? void 0 : options.enable) && enableChii && !resovedInfo.availablePort) {
654
- resovedInfo.availablePort = await getRandomPort();
655
- (0, import_z_chii.start)({ port: resovedInfo.availablePort });
656
- debug(`chii server port: ${resovedInfo.availablePort}`);
657
- }
658
- if ((options == null ? void 0 : options.enable) && enableChii) {
659
- const file = id.split("?")[0];
660
- if (file.startsWith((config == null ? void 0 : config.root) || cwd) && !file.includes("node_modules") && file.match(/\.[t|j]s$/)) {
661
- return {
662
- code: `import 'chii-client';
663
- ${source}`,
664
- map: null
665
- };
666
- }
667
- }
668
- return { code: source, map: null };
669
- },
670
- vite: {
671
- configResolved(_config) {
672
- config = _config;
673
- },
674
- transformIndexHtml(html) {
675
- if ((options == null ? void 0 : options.enable) && enableChii) {
676
- const tag = `<script type="module">import 'chii-client';</script>`;
677
- if (!html.includes(tag)) {
678
- return html.replace(
679
- "</body>",
680
- `</body>${tag}
681
- `
682
- );
683
- }
684
- }
685
- return html;
686
- },
687
- async configureServer(server) {
688
- var _a, _b;
689
- if (!(options == null ? void 0 : options.enable)) {
690
- return;
691
- }
692
- const _printUrls = server.printUrls.bind(server);
693
- let source = `localhost:${config.server.port || 5173}`;
694
- const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
695
- if (url) {
696
- const u = new URL(url);
697
- source = u.host;
698
- }
699
- const base = server.config.base || "/";
700
- const _targetUrl = (_b = options == null ? void 0 : options.targetUrl) != null ? _b : `http://${source}${base}`;
701
- server.printUrls = () => {
702
- _printUrls();
703
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
704
- "Open in dingtalk"
705
- )}: ${colorUrl(`http://${source}${base}open-dingtalk`)}`);
706
- if (enableChii) {
707
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
708
- "Click to open chrome devtools"
709
- )}: ${colorUrl(`http://${source}${base}__chrome_devtools`)}`);
710
- }
711
- };
712
- const targetURL = new URL(_targetUrl);
713
- targetURL.searchParams.append("ddtab", "true");
714
- if (options == null ? void 0 : options.corpId) {
715
- targetURL.searchParams.append("corpId", options.corpId);
716
- }
717
- if (options.debugCookies && options.debugCookies.length > 0) {
718
- server.middlewares.use((req, res, next) => {
719
- const cookies = import_cookie.default.parse(req.headers.cookie || "");
720
- for (const [name, value] of Object.entries(cookies)) {
721
- if (value && options.debugCookies && options.debugCookies.length > 0 && options.debugCookies.includes(name)) {
722
- const serializedCookie = import_cookie.default.serialize(name, value, {
723
- httpOnly: false
724
- });
725
- res.setHeader("Set-Cookie", serializedCookie);
726
- }
727
- }
728
- next();
729
- });
730
- }
731
- if (enableChii) {
732
- server.middlewares.use("/__chrome_devtools", async (_req, res) => {
733
- if (!resovedInfo.availablePort) {
734
- res.writeHead(500, { "Content-Type": "text/plain" });
735
- res.end("Server not started");
736
- return;
737
- }
738
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
739
- res.write(getChromeDevtoolsHtml(resovedInfo.availablePort));
740
- res.end();
741
- });
742
- const proxyMiddleware = createProxyMiddleware(debug);
743
- server.middlewares.use(proxyMiddleware(resovedInfo));
744
- }
745
- server.middlewares.use("/open-dingtalk", (req, res) => {
746
- debug(targetURL.toString());
747
- res.writeHead(302, {
748
- Location: `dingtalk://dingtalkclient/page/link?url=${encodeURIComponent(targetURL.toString())}`
749
- });
750
- res.end();
751
- });
752
- }
753
- },
754
- webpack(compiler) {
755
- var _a, _b;
756
- if (!(options == null ? void 0 : options.enable)) {
757
- return;
758
- }
759
- const devServerOptions = __spreadValues(__spreadValues({
760
- host: "localhost",
761
- port: 8080
762
- }, compiler.options.devServer), (_a = import_node_process.default.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
763
- const source = `${devServerOptions.host === "0.0.0.0" ? "127.0.0.1" : devServerOptions.host}:${devServerOptions.port}`;
764
- const base = compiler.options.output.publicPath || "/";
765
- const _targetUrl = (_b = options == null ? void 0 : options.targetUrl) != null ? _b : `http://${source}${base}`;
766
- compiler.hooks.done.tap("unplugin-dingtalk", () => {
767
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
768
- "Open in dingtalk"
769
- )}: ${colorUrl(`http://${source}${base}open-dingtalk`)}`);
770
- if (enableChii) {
771
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
772
- "Click to open chrome devtools"
773
- )}: ${colorUrl(`http://${source}${base}__chrome_devtools`)}`);
774
- }
775
- });
776
- resovedInfo.targetURL = new URL(_targetUrl);
777
- resovedInfo.targetURL.searchParams.append("ddtab", "true");
778
- if (options == null ? void 0 : options.corpId) {
779
- resovedInfo.targetURL.searchParams.append("corpId", options.corpId);
780
- }
781
- },
782
- async rspack(compiler) {
783
- var _a, _b, _c, _d;
784
- if (!(options == null ? void 0 : options.enable)) {
785
- return;
786
- }
787
- const devServerOptions = __spreadValues(__spreadValues({
788
- host: "localhost",
789
- port: 8080
790
- }, compiler.options.devServer), (_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
791
- cwd
792
- }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server);
793
- const source = `${devServerOptions.host === "0.0.0.0" ? "127.0.0.1" : devServerOptions.host}:${devServerOptions.port}`;
794
- const base = compiler.options.output.publicPath || "/";
795
- const _targetUrl = (_d = options == null ? void 0 : options.targetUrl) != null ? _d : `http://${source}${base}`;
796
- resovedInfo.targetURL = new URL(_targetUrl);
797
- resovedInfo.targetURL.searchParams.append("ddtab", "true");
798
- if (options == null ? void 0 : options.corpId) {
799
- resovedInfo.targetURL.searchParams.append("corpId", options.corpId);
800
- }
801
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
802
- "Open in dingtalk"
803
- )}: ${colorUrl(`http://${source}${base}open-dingtalk`)}`);
804
- if (enableChii) {
805
- console.log(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold(
806
- "Click to open chrome devtools"
807
- )}: ${colorUrl(`http://${source}${base}__chrome_devtools`)}`);
808
- }
809
- }
810
- };
811
- return unpluginDing;
812
- };
813
-
814
- // src/vite.ts
815
- var vite_default = async (options) => {
816
- var _a;
817
- const plugins = [(0, import_unplugin2.createVitePlugin)(unpluginFactory)(options)];
818
- if ((options == null ? void 0 : options.enable) && ((_a = options == null ? void 0 : options.vconsole) == null ? void 0 : _a.enabled)) {
819
- try {
820
- const viteVConsilePlugin = await interopDefault(Promise.resolve().then(() => (init_main(), main_exports)));
821
- plugins.push(viteVConsilePlugin(options == null ? void 0 : options.vconsole));
822
- } catch (e) {
823
- console.error("vite-plugin-vconsole not found");
824
- }
825
- }
826
- return plugins;
827
- };
299
+ async function sendProxy(event, target, opts = {}) {
300
+ let response;
301
+ try {
302
+ response = await _getFetch(opts.fetch)(target, {
303
+ headers: opts.headers,
304
+ ignoreResponseError: true,
305
+ ...opts.fetchOptions
306
+ });
307
+ } catch (error) {
308
+ throw createError({
309
+ status: 502,
310
+ statusMessage: "Bad Gateway",
311
+ cause: error
312
+ });
313
+ }
314
+ event.node.res.statusCode = sanitizeStatusCode(response.status, event.node.res.statusCode);
315
+ event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
316
+ const cookies = [];
317
+ for (const [key, value] of response.headers.entries()) {
318
+ if (key === "content-encoding") continue;
319
+ if (key === "content-length") continue;
320
+ if (key === "set-cookie") {
321
+ cookies.push(...splitCookiesString(value));
322
+ continue;
323
+ }
324
+ event.node.res.setHeader(key, value);
325
+ }
326
+ if (cookies.length > 0) event.node.res.setHeader("set-cookie", cookies.map((cookie) => {
327
+ if (opts.cookieDomainRewrite) cookie = rewriteCookieProperty(cookie, opts.cookieDomainRewrite, "domain");
328
+ if (opts.cookiePathRewrite) cookie = rewriteCookieProperty(cookie, opts.cookiePathRewrite, "path");
329
+ return cookie;
330
+ }));
331
+ if (opts.onResponse) await opts.onResponse(event, response);
332
+ if (response._data !== void 0) return response._data;
333
+ if (event.handled) return;
334
+ if (opts.sendStream === false) {
335
+ const data = new Uint8Array(await response.arrayBuffer());
336
+ return event.node.res.end(data);
337
+ }
338
+ if (response.body) for await (const chunk of response.body) event.node.res.write(chunk);
339
+ return event.node.res.end();
340
+ }
341
+ function getProxyRequestHeaders(event, opts) {
342
+ const headers = /* @__PURE__ */ Object.create(null);
343
+ const reqHeaders = getRequestHeaders(event);
344
+ for (const name in reqHeaders) if (!ignoredHeaders.has(name) || name === "host" && opts?.host) headers[name] = reqHeaders[name];
345
+ return headers;
346
+ }
347
+ function _getFetch(_fetch) {
348
+ if (_fetch) return _fetch;
349
+ if (globalThis.fetch) return globalThis.fetch;
350
+ throw new Error("fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js.");
351
+ }
352
+ function rewriteCookieProperty(header, map, property) {
353
+ const _map = typeof map === "string" ? { "*": map } : map;
354
+ return header.replace(new RegExp(`(;\\s*${property}=)([^;]+)`, "gi"), (match, prefix, previousValue) => {
355
+ let newValue;
356
+ if (previousValue in _map) newValue = _map[previousValue];
357
+ else if ("*" in _map) newValue = _map["*"];
358
+ else return match;
359
+ return newValue ? prefix + newValue : "";
360
+ });
361
+ }
362
+ function mergeHeaders(defaults, ...inputs) {
363
+ const _inputs = inputs.filter(Boolean);
364
+ if (_inputs.length === 0) return defaults;
365
+ const merged = new Headers(defaults);
366
+ for (const input of _inputs) {
367
+ const entries = Array.isArray(input) ? input : typeof input.entries === "function" ? input.entries() : Object.entries(input);
368
+ for (const [key, value] of entries) if (value !== void 0) merged.set(key, value);
369
+ }
370
+ return merged;
371
+ }
372
+ const getSessionPromise = Symbol("getSession");
373
+ function defineEventHandler(handler) {
374
+ if (typeof handler === "function") {
375
+ handler.__is_handler__ = true;
376
+ return handler;
377
+ }
378
+ const _hooks = {
379
+ onRequest: _normalizeArray(handler.onRequest),
380
+ onBeforeResponse: _normalizeArray(handler.onBeforeResponse)
381
+ };
382
+ const _handler = (event) => {
383
+ return _callHandler(event, handler.handler, _hooks);
384
+ };
385
+ _handler.__is_handler__ = true;
386
+ _handler.__resolve__ = handler.handler.__resolve__;
387
+ _handler.__websocket__ = handler.websocket;
388
+ return _handler;
389
+ }
390
+ function _normalizeArray(input) {
391
+ return input ? Array.isArray(input) ? input : [input] : void 0;
392
+ }
393
+ async function _callHandler(event, handler, hooks) {
394
+ if (hooks.onRequest) for (const hook of hooks.onRequest) {
395
+ await hook(event);
396
+ if (event.handled) return;
397
+ }
398
+ const body = await handler(event);
399
+ const response = { body };
400
+ if (hooks.onBeforeResponse) for (const hook of hooks.onBeforeResponse) await hook(event, response);
401
+ return response.body;
402
+ }
403
+ const H3Headers = globalThis.Headers;
404
+ const H3Response = globalThis.Response;
828
405
 
829
- // src/nuxt.ts
830
- var import_schema = require("@nuxt/schema");
831
- var nuxt_default = (0, import_kit.defineNuxtModule)({
832
- meta: {
833
- name: "nuxt-unplugin-dingtalk",
834
- configKey: "unpluginStarter"
835
- },
836
- defaults: {
837
- // ...default options
838
- },
839
- async setup(options, _nuxt) {
840
- const vitePlugins = await vite_default(options);
841
- (0, import_kit.addVitePlugin)(vitePlugins);
842
- }
406
+ //#endregion
407
+ //#region src/nuxt.ts
408
+ var nuxt_default = (0, __nuxt_kit.defineNuxtModule)({
409
+ meta: {
410
+ name: "nuxt-unplugin-dingtalk",
411
+ configKey: "unpluginDingtalk"
412
+ },
413
+ defaults: {},
414
+ async setup(options, _nuxt) {
415
+ if (!_nuxt.options.dev) return;
416
+ if (!options.enable) return;
417
+ function debug(...args) {
418
+ if (options?.debug) console.log(` ${picocolors.default.yellow("DEBUG")} `, ...args);
419
+ }
420
+ const { chii } = options || {};
421
+ const enableChii = chii?.enable !== false;
422
+ _nuxt.options.runtimeConfig.unpluginDingtalk = { chiiEmbedded: chii?.embedded ?? false };
423
+ if (enableChii) {
424
+ const resolver = (0, __nuxt_kit.createResolver)(require("url").pathToFileURL(__filename).href);
425
+ (0, __nuxt_kit.addServerPlugin)(resolver.resolve("./inject-script"));
426
+ let proxy = null;
427
+ (0, __nuxt_kit.addDevServerHandler)({
428
+ route: "/__chii_proxy",
429
+ handler: defineEventHandler(async (event) => {
430
+ if (require_src.resovedInfo.availablePort) return proxyRequest(event, `http://localhost:${require_src.resovedInfo.availablePort}${event.path}`);
431
+ })
432
+ });
433
+ _nuxt.hook("listen", (server) => {
434
+ const originalUpgradeListeners = server.listeners("upgrade").slice();
435
+ server.removeAllListeners("upgrade");
436
+ server.on("upgrade", (req, socket, head) => {
437
+ if (req.url?.startsWith("/__chii_proxy")) {
438
+ debug("WS upgrade:", req.url);
439
+ if (!proxy && require_src.resovedInfo.availablePort) {
440
+ proxy = http_proxy.default.createProxyServer({
441
+ target: `http://localhost:${require_src.resovedInfo.availablePort}`,
442
+ ws: true
443
+ });
444
+ proxy.on("error", (err) => {
445
+ debug("Proxy error:", err.message);
446
+ });
447
+ }
448
+ if (proxy) {
449
+ req.url = req.url.replace("/__chii_proxy", "");
450
+ socket.on("error", (err) => {
451
+ debug("Socket error:", err.message);
452
+ });
453
+ try {
454
+ proxy.ws(req, socket, head);
455
+ } catch (err) {
456
+ debug("WS upgrade failed:", err.message);
457
+ socket.destroy();
458
+ }
459
+ return;
460
+ }
461
+ }
462
+ for (const listener of originalUpgradeListeners) listener.call(server, req, socket, head);
463
+ });
464
+ });
465
+ }
466
+ const vitePlugins = await require_vite.vite_default(options);
467
+ (0, __nuxt_kit.addVitePlugin)(vitePlugins);
468
+ _nuxt.hook("listen", (_, listener) => {
469
+ const url = listener.url;
470
+ const source = new URL(url).host;
471
+ const base = _nuxt.options.app.baseURL || "/";
472
+ if (enableChii) console.log(` ${picocolors.default.green("➜")} ${picocolors.default.bold("Click to open chrome devtools")}: ${require_utils.colorUrl(`http://${source}${base}__chrome_devtools`)}`);
473
+ });
474
+ }
843
475
  });
844
- exports.default = module.exports;
476
+
477
+ //#endregion
478
+ module.exports = nuxt_default;