@ubiquity-os/plugin-sdk 3.8.0 → 3.8.4

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 CHANGED
@@ -41,487 +41,39 @@ module.exports = __toCommonJS(src_exports);
41
41
 
42
42
  // src/actions.ts
43
43
  var core = __toESM(require("@actions/core"));
44
+ var github2 = __toESM(require("@actions/github"));
44
45
  var import_value3 = require("@sinclair/typebox/value");
45
-
46
- // ../../node_modules/@ubiquity-os/ubiquity-os-logger/dist/index.js
47
- var COLORS = {
48
- reset: "\x1B[0m",
49
- bright: "\x1B[1m",
50
- dim: "\x1B[2m",
51
- underscore: "\x1B[4m",
52
- blink: "\x1B[5m",
53
- reverse: "\x1B[7m",
54
- hidden: "\x1B[8m",
55
- fgBlack: "\x1B[30m",
56
- fgRed: "\x1B[31m",
57
- fgGreen: "\x1B[32m",
58
- fgYellow: "\x1B[33m",
59
- fgBlue: "\x1B[34m",
60
- fgMagenta: "\x1B[35m",
61
- fgCyan: "\x1B[36m",
62
- fgWhite: "\x1B[37m",
63
- bgBlack: "\x1B[40m",
64
- bgRed: "\x1B[41m",
65
- bgGreen: "\x1B[42m",
66
- bgYellow: "\x1B[43m",
67
- bgBlue: "\x1B[44m",
68
- bgMagenta: "\x1B[45m",
69
- bgCyan: "\x1B[46m",
70
- bgWhite: "\x1B[47m"
71
- };
72
- var LOG_LEVEL = {
73
- FATAL: "fatal",
74
- ERROR: "error",
75
- WARN: "warn",
76
- INFO: "info",
77
- VERBOSE: "verbose",
78
- DEBUG: "debug"
79
- };
80
- var PrettyLogs = class {
81
- constructor() {
82
- this.ok = this.ok.bind(this);
83
- this.info = this.info.bind(this);
84
- this.error = this.error.bind(this);
85
- this.fatal = this.fatal.bind(this);
86
- this.warn = this.warn.bind(this);
87
- this.debug = this.debug.bind(this);
88
- this.verbose = this.verbose.bind(this);
89
- }
90
- fatal(message, metadata) {
91
- this._logWithStack(LOG_LEVEL.FATAL, message, metadata);
92
- }
93
- error(message, metadata) {
94
- this._logWithStack(LOG_LEVEL.ERROR, message, metadata);
95
- }
96
- warn(message, metadata) {
97
- this._logWithStack(LOG_LEVEL.WARN, message, metadata);
98
- }
99
- ok(message, metadata) {
100
- this._logWithStack("ok", message, metadata);
101
- }
102
- info(message, metadata) {
103
- this._logWithStack(LOG_LEVEL.INFO, message, metadata);
104
- }
105
- debug(message, metadata) {
106
- this._logWithStack(LOG_LEVEL.DEBUG, message, metadata);
107
- }
108
- verbose(message, metadata) {
109
- this._logWithStack(LOG_LEVEL.VERBOSE, message, metadata);
110
- }
111
- _logWithStack(type, message, metaData) {
112
- this._log(type, message);
113
- if (typeof metaData === "string") {
114
- this._log(type, metaData);
115
- return;
116
- }
117
- if (metaData) {
118
- const metadata = metaData;
119
- let stack = metadata?.error?.stack || metadata?.stack;
120
- if (!stack) {
121
- const stackTrace = new Error().stack?.split("\n");
122
- if (stackTrace) {
123
- stackTrace.splice(0, 4);
124
- stack = stackTrace.filter((line) => line.includes(".ts:")).join("\n");
125
- }
126
- }
127
- const newMetadata = { ...metadata };
128
- delete newMetadata.message;
129
- delete newMetadata.name;
130
- delete newMetadata.stack;
131
- if (!this._isEmpty(newMetadata)) {
132
- this._log(type, newMetadata);
133
- }
134
- if (typeof stack == "string") {
135
- const prettyStack = this._formatStackTrace(stack, 1);
136
- const colorizedStack = this._colorizeText(prettyStack, COLORS.dim);
137
- this._log(type, colorizedStack);
138
- } else if (stack) {
139
- const prettyStack = this._formatStackTrace(stack.join("\n"), 1);
140
- const colorizedStack = this._colorizeText(prettyStack, COLORS.dim);
141
- this._log(type, colorizedStack);
142
- } else {
143
- throw new Error("Stack is null");
144
- }
145
- }
146
- }
147
- _colorizeText(text, color) {
148
- if (!color) {
149
- throw new Error(`Invalid color: ${color}`);
150
- }
151
- return color.concat(text).concat(COLORS.reset);
152
- }
153
- _formatStackTrace(stack, linesToRemove = 0, prefix = "") {
154
- const lines = stack.split("\n");
155
- for (let i = 0; i < linesToRemove; i++) {
156
- lines.shift();
157
- }
158
- return lines.map((line) => `${prefix}${line.replace(/\s*at\s*/, " \u21B3 ")}`).join("\n");
159
- }
160
- _isEmpty(obj) {
161
- return !Reflect.ownKeys(obj).some((key) => typeof obj[String(key)] !== "function");
162
- }
163
- _log(type, message) {
164
- const defaultSymbols = {
165
- fatal: "\xD7",
166
- ok: "\u2713",
167
- warn: "\u26A0",
168
- error: "\u26A0",
169
- info: "\u203A",
170
- debug: "\u203A\u203A",
171
- verbose: "\u{1F4AC}"
172
- };
173
- const symbol = defaultSymbols[type];
174
- const messageFormatted = typeof message === "string" ? message : JSON.stringify(message, null, 2);
175
- const lines = messageFormatted.split("\n");
176
- const logString = lines.map((line, index) => {
177
- const prefix = index === 0 ? ` ${symbol}` : ` ${" ".repeat(symbol.length)}`;
178
- return `${prefix} ${line}`;
179
- }).join("\n");
180
- const fullLogString = logString;
181
- const colorMap = {
182
- fatal: ["error", COLORS.fgRed],
183
- ok: ["log", COLORS.fgGreen],
184
- warn: ["warn", COLORS.fgYellow],
185
- error: ["warn", COLORS.fgYellow],
186
- info: ["info", COLORS.dim],
187
- debug: ["debug", COLORS.fgMagenta],
188
- verbose: ["debug", COLORS.dim]
189
- };
190
- const _console = console[colorMap[type][0]];
191
- if (typeof _console === "function" && fullLogString.length > 12) {
192
- _console(this._colorizeText(fullLogString, colorMap[type][1]));
193
- } else if (fullLogString.length <= 12) {
194
- return;
195
- } else {
196
- throw new Error(fullLogString);
197
- }
198
- }
199
- };
200
- var LogReturn = class {
201
- logMessage;
202
- metadata;
203
- constructor(logMessage, metadata) {
204
- this.logMessage = logMessage;
205
- this.metadata = metadata;
206
- }
207
- };
208
- var Logs = class _Logs {
209
- _maxLevel = -1;
210
- static console;
211
- _log({ level, consoleLog, logMessage, metadata, type }) {
212
- if (this._getNumericLevel(level) <= this._maxLevel) {
213
- consoleLog(logMessage, metadata);
214
- }
215
- return new LogReturn(
216
- {
217
- raw: logMessage,
218
- diff: this._diffColorCommentMessage(type, logMessage),
219
- type,
220
- level
221
- },
222
- metadata
223
- );
224
- }
225
- _addDiagnosticInformation(metadata) {
226
- if (!metadata) {
227
- metadata = {};
228
- } else if (typeof metadata !== "object") {
229
- metadata = { message: metadata };
230
- }
231
- const stackLines = new Error().stack?.split("\n") || [];
232
- if (stackLines.length > 3) {
233
- const callerLine = stackLines[3];
234
- const match2 = callerLine.match(/at (\S+)/);
235
- if (match2) {
236
- metadata.caller = match2[1];
237
- }
238
- }
239
- return metadata;
240
- }
241
- ok(log, metadata) {
242
- metadata = this._addDiagnosticInformation(metadata);
243
- return this._log({
244
- level: LOG_LEVEL.INFO,
245
- consoleLog: _Logs.console.ok,
246
- logMessage: log,
247
- metadata,
248
- type: "ok"
249
- });
250
- }
251
- info(log, metadata) {
252
- metadata = this._addDiagnosticInformation(metadata);
253
- return this._log({
254
- level: LOG_LEVEL.INFO,
255
- consoleLog: _Logs.console.info,
256
- logMessage: log,
257
- metadata,
258
- type: "info"
259
- });
260
- }
261
- warn(log, metadata) {
262
- metadata = this._addDiagnosticInformation(metadata);
263
- return this._log({
264
- level: LOG_LEVEL.WARN,
265
- consoleLog: _Logs.console.warn,
266
- logMessage: log,
267
- metadata,
268
- type: "warn"
269
- });
270
- }
271
- error(log, metadata) {
272
- metadata = this._addDiagnosticInformation(metadata);
273
- return this._log({
274
- level: LOG_LEVEL.ERROR,
275
- consoleLog: _Logs.console.error,
276
- logMessage: log,
277
- metadata,
278
- type: "error"
279
- });
280
- }
281
- debug(log, metadata) {
282
- metadata = this._addDiagnosticInformation(metadata);
283
- return this._log({
284
- level: LOG_LEVEL.DEBUG,
285
- consoleLog: _Logs.console.debug,
286
- logMessage: log,
287
- metadata,
288
- type: "debug"
289
- });
290
- }
291
- fatal(log, metadata) {
292
- if (!metadata) {
293
- metadata = _Logs.convertErrorsIntoObjects(new Error(log));
294
- const stack = metadata.stack;
295
- stack.splice(1, 1);
296
- metadata.stack = stack;
297
- }
298
- if (metadata instanceof Error) {
299
- metadata = _Logs.convertErrorsIntoObjects(metadata);
300
- const stack = metadata.stack;
301
- stack.splice(1, 1);
302
- metadata.stack = stack;
303
- }
304
- metadata = this._addDiagnosticInformation(metadata);
305
- return this._log({
306
- level: LOG_LEVEL.FATAL,
307
- consoleLog: _Logs.console.fatal,
308
- logMessage: log,
309
- metadata,
310
- type: "fatal"
311
- });
312
- }
313
- verbose(log, metadata) {
314
- metadata = this._addDiagnosticInformation(metadata);
315
- return this._log({
316
- level: LOG_LEVEL.VERBOSE,
317
- consoleLog: _Logs.console.verbose,
318
- logMessage: log,
319
- metadata,
320
- type: "verbose"
321
- });
322
- }
323
- constructor(logLevel) {
324
- this._maxLevel = this._getNumericLevel(logLevel);
325
- _Logs.console = new PrettyLogs();
326
- }
327
- _diffColorCommentMessage(type, message) {
328
- const diffPrefix = {
329
- fatal: "> [!CAUTION]",
330
- error: "> [!CAUTION]",
331
- warn: "> [!WARNING]",
332
- ok: "> [!TIP]",
333
- info: "> [!NOTE]",
334
- debug: "> [!IMPORTANT]",
335
- verbose: "> [!NOTE]"
336
- };
337
- const selected = diffPrefix[type];
338
- if (selected) {
339
- message = message.trim().split("\n").map((line) => `> ${line}`).join("\n");
340
- }
341
- return [selected, message].join("\n");
342
- }
343
- _getNumericLevel(level) {
344
- switch (level) {
345
- case LOG_LEVEL.FATAL:
346
- return 0;
347
- case LOG_LEVEL.ERROR:
348
- return 1;
349
- case LOG_LEVEL.WARN:
350
- return 2;
351
- case LOG_LEVEL.INFO:
352
- return 3;
353
- case LOG_LEVEL.VERBOSE:
354
- return 4;
355
- case LOG_LEVEL.DEBUG:
356
- return 5;
357
- default:
358
- return -1;
359
- }
360
- }
361
- static convertErrorsIntoObjects(obj) {
362
- if (obj instanceof Error) {
363
- return {
364
- message: obj.message,
365
- name: obj.name,
366
- stack: obj.stack ? obj.stack.split("\n") : null
367
- };
368
- } else if (typeof obj === "object" && obj !== null) {
369
- const keys = Object.keys(obj);
370
- keys.forEach((key) => {
371
- obj[key] = this.convertErrorsIntoObjects(obj[key]);
372
- });
373
- }
374
- return obj;
375
- }
376
- };
377
-
378
- // src/actions.ts
379
- var import_dotenv = require("dotenv");
380
-
381
- // src/error.ts
382
- function getErrorStatus(err) {
383
- if (!err || typeof err !== "object") return null;
384
- const candidate = err;
385
- const directStatus = candidate.status ?? candidate.response?.status;
386
- if (typeof directStatus === "number" && Number.isFinite(directStatus)) return directStatus;
387
- if (typeof directStatus === "string" && directStatus.trim()) {
388
- const parsed = Number.parseInt(directStatus, 10);
389
- if (Number.isFinite(parsed)) return parsed;
390
- }
391
- if (err instanceof Error) {
392
- const match2 = /LLM API error:\s*(\d{3})/i.exec(err.message);
393
- if (match2) {
394
- const parsed = Number.parseInt(match2[1], 10);
395
- if (Number.isFinite(parsed)) return parsed;
396
- }
397
- }
398
- return null;
399
- }
400
- function logByStatus(context, message, metadata) {
401
- const status = getErrorStatus(metadata.err);
402
- const payload = { ...metadata, ...status ? { status } : {} };
403
- if (status && status >= 500) return context.logger.error(message, payload);
404
- if (status && status >= 400) return context.logger.warn(message, payload);
405
- if (status && status >= 300) return context.logger.debug(message, payload);
406
- if (status && status >= 200) return context.logger.ok(message, payload);
407
- if (status && status >= 100) return context.logger.info(message, payload);
408
- return context.logger.error(message, payload);
409
- }
410
- function transformError(context, error) {
411
- if (error instanceof LogReturn) {
412
- return error;
413
- }
414
- if (error instanceof AggregateError) {
415
- const message = error.errors.map((err) => {
416
- if (err instanceof LogReturn) {
417
- return err.logMessage.raw;
418
- }
419
- if (err instanceof Error) {
420
- return err.message;
421
- }
422
- return String(err);
423
- }).join("\n\n");
424
- return logByStatus(context, message, { err: error });
425
- }
426
- if (error instanceof Error) {
427
- return logByStatus(context, error.message, { err: error });
428
- }
429
- return logByStatus(context, String(error), { err: error });
430
- }
431
-
432
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/helper/adapter/index.js
433
- var env = (c, runtime) => {
434
- const global = globalThis;
435
- const globalEnv = global?.process?.env;
436
- runtime ??= getRuntimeKey();
437
- const runtimeEnvHandlers = {
438
- bun: () => globalEnv,
439
- node: () => globalEnv,
440
- "edge-light": () => globalEnv,
441
- deno: () => {
442
- return Deno.env.toObject();
443
- },
444
- workerd: () => c.env,
445
- // On Fastly Compute, you can use the ConfigStore to manage user-defined data.
446
- fastly: () => ({}),
447
- other: () => ({})
448
- };
449
- return runtimeEnvHandlers[runtime]();
450
- };
451
- var knownUserAgents = {
452
- deno: "Deno",
453
- bun: "Bun",
454
- workerd: "Cloudflare-Workers",
455
- node: "Node.js"
456
- };
457
- var getRuntimeKey = () => {
458
- const global = globalThis;
459
- const userAgentSupported = typeof navigator !== "undefined" && typeof navigator.userAgent === "string";
460
- if (userAgentSupported) {
461
- for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) {
462
- if (checkUserAgentEquals(userAgent)) {
463
- return runtimeKey;
464
- }
465
- }
466
- }
467
- if (typeof global?.EdgeRuntime === "string") {
468
- return "edge-light";
469
- }
470
- if (global?.fastly !== void 0) {
471
- return "fastly";
472
- }
473
- if (global?.process?.release?.name === "node") {
474
- return "node";
475
- }
476
- return "other";
477
- };
478
- var checkUserAgentEquals = (platform) => {
479
- const userAgent = navigator.userAgent;
480
- return userAgent.startsWith(platform);
481
- };
482
-
483
- // src/helpers/github-context.ts
484
- var github = __toESM(require("@actions/github"));
485
- function getGithubContext() {
486
- const override = globalThis.__UOS_GITHUB_CONTEXT__;
487
- if (override) {
488
- return override;
489
- }
490
- const module2 = github;
491
- const context = module2.context ?? module2.default?.context;
492
- if (!context) {
493
- throw new Error("GitHub context is unavailable.");
494
- }
495
- return context;
496
- }
46
+ var import_ubiquity_os_logger3 = require("@ubiquity-os/ubiquity-os-logger");
497
47
 
498
48
  // src/helpers/runtime-info.ts
49
+ var import_github = __toESM(require("@actions/github"));
50
+ var import_adapter = require("hono/adapter");
499
51
  var PluginRuntimeInfo = class _PluginRuntimeInfo {
500
52
  static _instance = null;
501
53
  _env = {};
502
- constructor(env2) {
503
- if (env2) {
504
- this._env = env2;
54
+ constructor(env) {
55
+ if (env) {
56
+ this._env = env;
505
57
  }
506
58
  }
507
- static getInstance(env2) {
59
+ static getInstance(env) {
508
60
  if (!_PluginRuntimeInfo._instance) {
509
- switch (getRuntimeKey()) {
61
+ switch ((0, import_adapter.getRuntimeKey)()) {
510
62
  case "workerd":
511
- _PluginRuntimeInfo._instance = new CfRuntimeInfo(env2);
63
+ _PluginRuntimeInfo._instance = new CfRuntimeInfo(env);
512
64
  break;
513
65
  case "deno":
514
66
  if (process.env.CI) {
515
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
67
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
516
68
  } else {
517
- _PluginRuntimeInfo._instance = new DenoRuntimeInfo(env2);
69
+ _PluginRuntimeInfo._instance = new DenoRuntimeInfo(env);
518
70
  }
519
71
  break;
520
72
  case "node":
521
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
73
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
522
74
  break;
523
75
  default:
524
- _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env2);
76
+ _PluginRuntimeInfo._instance = new NodeRuntimeInfo(env);
525
77
  break;
526
78
  }
527
79
  }
@@ -543,11 +95,10 @@ var CfRuntimeInfo = class extends PluginRuntimeInfo {
543
95
  };
544
96
  var NodeRuntimeInfo = class extends PluginRuntimeInfo {
545
97
  get version() {
546
- return getGithubContext().sha;
98
+ return import_github.default.context.sha;
547
99
  }
548
100
  get runUrl() {
549
- const context = getGithubContext();
550
- return context.payload.repository ? `${context.payload.repository?.html_url}/actions/runs/${context.runId}` : "http://localhost";
101
+ return import_github.default.context.payload.repository ? `${import_github.default.context.payload.repository?.html_url}/actions/runs/${import_github.default.context.runId}` : "http://localhost";
551
102
  }
552
103
  };
553
104
  var DenoRuntimeInfo = class extends PluginRuntimeInfo {
@@ -587,6 +138,9 @@ var DenoRuntimeInfo = class extends PluginRuntimeInfo {
587
138
  }
588
139
  };
589
140
 
141
+ // src/util.ts
142
+ var import_ubiquity_os_logger = require("@ubiquity-os/ubiquity-os-logger");
143
+
590
144
  // src/constants.ts
591
145
  var KERNEL_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
592
146
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs96DOU+JqM8SyNXOB6u3
@@ -625,7 +179,7 @@ function getPluginOptions(options) {
625
179
  return {
626
180
  // Important to use || and not ?? to not consider empty strings
627
181
  kernelPublicKey: options?.kernelPublicKey || KERNEL_PUBLIC_KEY,
628
- logLevel: options?.logLevel || LOG_LEVEL.INFO,
182
+ logLevel: options?.logLevel || import_ubiquity_os_logger.LOG_LEVEL.INFO,
629
183
  postCommentOnError: options?.postCommentOnError ?? true,
630
184
  settingsSchema: options?.settingsSchema,
631
185
  envSchema: options?.envSchema,
@@ -637,72 +191,14 @@ function getPluginOptions(options) {
637
191
  }
638
192
 
639
193
  // src/comment.ts
640
- var COMMAND_RESPONSE_KIND = "command-response";
641
- var COMMAND_RESPONSE_MARKER = `"commentKind": "${COMMAND_RESPONSE_KIND}"`;
642
- var COMMAND_RESPONSE_COMMENT_LIMIT = 50;
643
- var RECENT_COMMENTS_QUERY = `
644
- query($owner: String!, $repo: String!, $number: Int!, $last: Int!) {
645
- repository(owner: $owner, name: $repo) {
646
- issueOrPullRequest(number: $number) {
647
- __typename
648
- ... on Issue {
649
- comments(last: $last) {
650
- nodes {
651
- id
652
- body
653
- isMinimized
654
- minimizedReason
655
- author {
656
- login
657
- }
658
- }
659
- }
660
- }
661
- ... on PullRequest {
662
- comments(last: $last) {
663
- nodes {
664
- id
665
- body
666
- isMinimized
667
- minimizedReason
668
- author {
669
- login
670
- }
671
- }
672
- }
673
- }
674
- }
675
- }
676
- }
677
- `;
678
- var MINIMIZE_COMMENT_MUTATION = `
679
- mutation($id: ID!, $classifier: ReportedContentClassifiers!) {
680
- minimizeComment(input: { subjectId: $id, classifier: $classifier }) {
681
- minimizedComment {
682
- isMinimized
683
- minimizedReason
684
- }
685
- }
686
- }
687
- `;
688
- function logByStatus2(logger, message, status, metadata) {
689
- const payload = { ...metadata, ...status ? { status } : {} };
690
- if (status && status >= 500) return logger.error(message, payload);
691
- if (status && status >= 400) return logger.warn(message, payload);
692
- if (status && status >= 300) return logger.debug(message, payload);
693
- if (status && status >= 200) return logger.ok(message, payload);
694
- if (status && status >= 100) return logger.info(message, payload);
695
- return logger.error(message, payload);
696
- }
697
194
  var CommentHandler = class _CommentHandler {
698
195
  static HEADER_NAME = "UbiquityOS";
699
196
  _lastCommentId = { reviewCommentId: null, issueCommentId: null };
700
- _commandResponsePolicyApplied = false;
701
- async _updateIssueComment(context, params) {
197
+ async _updateIssueComment(context2, params) {
702
198
  if (!this._lastCommentId.issueCommentId) {
703
- throw context.logger.error("issueCommentId is missing");
199
+ throw context2.logger.error("issueCommentId is missing");
704
200
  }
705
- const commentData = await context.octokit.rest.issues.updateComment({
201
+ const commentData = await context2.octokit.rest.issues.updateComment({
706
202
  owner: params.owner,
707
203
  repo: params.repo,
708
204
  comment_id: this._lastCommentId.issueCommentId,
@@ -710,11 +206,11 @@ var CommentHandler = class _CommentHandler {
710
206
  });
711
207
  return { ...commentData.data, issueNumber: params.issueNumber };
712
208
  }
713
- async _updateReviewComment(context, params) {
209
+ async _updateReviewComment(context2, params) {
714
210
  if (!this._lastCommentId.reviewCommentId) {
715
- throw context.logger.error("reviewCommentId is missing");
211
+ throw context2.logger.error("reviewCommentId is missing");
716
212
  }
717
- const commentData = await context.octokit.rest.pulls.updateReviewComment({
213
+ const commentData = await context2.octokit.rest.pulls.updateReviewComment({
718
214
  owner: params.owner,
719
215
  repo: params.repo,
720
216
  comment_id: this._lastCommentId.reviewCommentId,
@@ -722,9 +218,9 @@ var CommentHandler = class _CommentHandler {
722
218
  });
723
219
  return { ...commentData.data, issueNumber: params.issueNumber };
724
220
  }
725
- async _createNewComment(context, params) {
221
+ async _createNewComment(context2, params) {
726
222
  if (params.commentId) {
727
- const commentData2 = await context.octokit.rest.pulls.createReplyForReviewComment({
223
+ const commentData2 = await context2.octokit.rest.pulls.createReplyForReviewComment({
728
224
  owner: params.owner,
729
225
  repo: params.repo,
730
226
  pull_number: params.issueNumber,
@@ -734,7 +230,7 @@ var CommentHandler = class _CommentHandler {
734
230
  this._lastCommentId.reviewCommentId = commentData2.data.id;
735
231
  return { ...commentData2.data, issueNumber: params.issueNumber };
736
232
  }
737
- const commentData = await context.octokit.rest.issues.createComment({
233
+ const commentData = await context2.octokit.rest.issues.createComment({
738
234
  owner: params.owner,
739
235
  repo: params.repo,
740
236
  issue_number: params.issueNumber,
@@ -743,143 +239,54 @@ var CommentHandler = class _CommentHandler {
743
239
  this._lastCommentId.issueCommentId = commentData.data.id;
744
240
  return { ...commentData.data, issueNumber: params.issueNumber };
745
241
  }
746
- _getIssueNumber(context) {
747
- if ("issue" in context.payload) return context.payload.issue.number;
748
- if ("pull_request" in context.payload) return context.payload.pull_request.number;
749
- if ("discussion" in context.payload) return context.payload.discussion.number;
242
+ _getIssueNumber(context2) {
243
+ if ("issue" in context2.payload) return context2.payload.issue.number;
244
+ if ("pull_request" in context2.payload) return context2.payload.pull_request.number;
245
+ if ("discussion" in context2.payload) return context2.payload.discussion.number;
750
246
  return void 0;
751
247
  }
752
- _getCommentId(context) {
753
- return "pull_request" in context.payload && "comment" in context.payload ? context.payload.comment.id : void 0;
754
- }
755
- _getCommentNodeId(context) {
756
- const payload = context.payload;
757
- const nodeId = payload.comment?.node_id;
758
- return typeof nodeId === "string" && nodeId.trim() ? nodeId : null;
248
+ _getCommentId(context2) {
249
+ return "pull_request" in context2.payload && "comment" in context2.payload ? context2.payload.comment.id : void 0;
759
250
  }
760
- _extractIssueContext(context) {
761
- if (!("repository" in context.payload) || !context.payload.repository?.owner?.login) {
251
+ _extractIssueContext(context2) {
252
+ if (!("repository" in context2.payload) || !context2.payload.repository?.owner?.login) {
762
253
  return null;
763
254
  }
764
- const issueNumber = this._getIssueNumber(context);
255
+ const issueNumber = this._getIssueNumber(context2);
765
256
  if (!issueNumber) return null;
766
257
  return {
767
258
  issueNumber,
768
- commentId: this._getCommentId(context),
769
- owner: context.payload.repository.owner.login,
770
- repo: context.payload.repository.name
771
- };
772
- }
773
- _extractIssueLocator(context) {
774
- if (!("issue" in context.payload) && !("pull_request" in context.payload)) {
775
- return null;
776
- }
777
- const issueContext = this._extractIssueContext(context);
778
- if (!issueContext) return null;
779
- return {
780
- owner: issueContext.owner,
781
- repo: issueContext.repo,
782
- issueNumber: issueContext.issueNumber
259
+ commentId: this._getCommentId(context2),
260
+ owner: context2.payload.repository.owner.login,
261
+ repo: context2.payload.repository.name
783
262
  };
784
263
  }
785
- _shouldApplyCommandResponsePolicy(context) {
786
- const payload = context;
787
- return Boolean(payload.command);
788
- }
789
- _isCommandResponseComment(body) {
790
- return typeof body === "string" && body.includes(COMMAND_RESPONSE_MARKER);
791
- }
792
- _getGraphqlClient(context) {
793
- const graphql = context.octokit.graphql;
794
- return typeof graphql === "function" ? graphql : null;
795
- }
796
- async _fetchRecentComments(context, locator, last = COMMAND_RESPONSE_COMMENT_LIMIT) {
797
- const graphql = this._getGraphqlClient(context);
798
- if (!graphql) return [];
799
- try {
800
- const data = await graphql(RECENT_COMMENTS_QUERY, {
801
- owner: locator.owner,
802
- repo: locator.repo,
803
- number: locator.issueNumber,
804
- last
805
- });
806
- const nodes = data.repository?.issueOrPullRequest?.comments?.nodes ?? [];
807
- return nodes.filter((node) => Boolean(node));
808
- } catch (error) {
809
- context.logger.debug("Failed to fetch recent comments (non-fatal)", { err: error });
810
- return [];
811
- }
812
- }
813
- _findPreviousCommandResponseComment(comments, currentCommentId) {
814
- for (let idx = comments.length - 1; idx >= 0; idx -= 1) {
815
- const comment = comments[idx];
816
- if (!comment) continue;
817
- if (currentCommentId && comment.id === currentCommentId) continue;
818
- if (this._isCommandResponseComment(comment.body)) {
819
- return comment;
820
- }
821
- }
822
- return null;
823
- }
824
- async _minimizeComment(context, commentNodeId, classifier = "RESOLVED") {
825
- const graphql = this._getGraphqlClient(context);
826
- if (!graphql) return;
827
- try {
828
- await graphql(MINIMIZE_COMMENT_MUTATION, {
829
- id: commentNodeId,
830
- classifier
831
- });
832
- } catch (error) {
833
- context.logger.debug("Failed to minimize comment (non-fatal)", { err: error, commentNodeId });
834
- }
835
- }
836
- async _applyCommandResponsePolicy(context) {
837
- if (this._commandResponsePolicyApplied) return;
838
- this._commandResponsePolicyApplied = true;
839
- if (!this._shouldApplyCommandResponsePolicy(context)) return;
840
- const locator = this._extractIssueLocator(context);
841
- const commentNodeId = this._getCommentNodeId(context);
842
- const comments = locator ? await this._fetchRecentComments(context, locator) : [];
843
- const current = commentNodeId ? comments.find((comment) => comment.id === commentNodeId) : null;
844
- const currentIsMinimized = current?.isMinimized ?? false;
845
- if (commentNodeId && !currentIsMinimized) {
846
- await this._minimizeComment(context, commentNodeId);
847
- }
848
- const previous = this._findPreviousCommandResponseComment(comments, commentNodeId);
849
- if (previous && !previous.isMinimized) {
850
- await this._minimizeComment(context, previous.id);
851
- }
852
- }
853
- _processMessage(context, message) {
264
+ _processMessage(context2, message) {
854
265
  if (message instanceof Error) {
855
266
  const metadata2 = {
856
267
  message: message.message,
857
268
  name: message.name,
858
269
  stack: message.stack
859
270
  };
860
- const status = getErrorStatus(message);
861
- const logReturn = logByStatus2(context.logger, message.message, status, metadata2);
862
- return { metadata: { ...metadata2, ...status ? { status } : {} }, logMessage: logReturn.logMessage };
271
+ return { metadata: metadata2, logMessage: context2.logger.error(message.message).logMessage };
863
272
  }
864
- const stackLine = message.metadata?.error?.stack?.split("\n")[2];
865
- const callerMatch = stackLine ? /at (\S+)/.exec(stackLine) : null;
866
273
  const metadata = message.metadata ? {
867
274
  ...message.metadata,
868
275
  message: message.metadata.message,
869
276
  stack: message.metadata.stack || message.metadata.error?.stack,
870
- caller: message.metadata.caller || callerMatch?.[1]
277
+ caller: message.metadata.caller || message.metadata.error?.stack?.split("\n")[2]?.match(/at (\S+)/)?.[1]
871
278
  } : { ...message };
872
279
  return { metadata, logMessage: message.logMessage };
873
280
  }
874
- _getInstigatorName(context) {
875
- if ("installation" in context.payload && context.payload.installation && "account" in context.payload.installation && context.payload.installation?.account?.name) {
876
- return context.payload.installation?.account?.name;
281
+ _getInstigatorName(context2) {
282
+ if ("installation" in context2.payload && context2.payload.installation && "account" in context2.payload.installation && context2.payload.installation?.account?.name) {
283
+ return context2.payload.installation?.account?.name;
877
284
  }
878
- return context.payload.sender?.login || _CommentHandler.HEADER_NAME;
285
+ return context2.payload.sender?.login || _CommentHandler.HEADER_NAME;
879
286
  }
880
- _createMetadataContent(context, metadata) {
287
+ _createMetadataContent(context2, metadata) {
881
288
  const jsonPretty = sanitizeMetadata(metadata);
882
- const instigatorName = this._getInstigatorName(context);
289
+ const instigatorName = this._getInstigatorName(context2);
883
290
  const runUrl = PluginRuntimeInfo.getInstance().runUrl;
884
291
  const version = PluginRuntimeInfo.getInstance().version;
885
292
  const callingFnName = metadata.caller || "anonymous";
@@ -896,46 +303,64 @@ var CommentHandler = class _CommentHandler {
896
303
  /*
897
304
  * Creates the body for the comment, embeds the metadata and the header hidden in the body as well.
898
305
  */
899
- createCommentBody(context, message, options) {
900
- return this._createCommentBody(context, message, options);
306
+ createCommentBody(context2, message, options) {
307
+ return this._createCommentBody(context2, message, options);
901
308
  }
902
- _createCommentBody(context, message, options) {
903
- const { metadata, logMessage } = this._processMessage(context, message);
904
- const shouldTagCommandResponse = options?.commentKind && typeof metadata === "object" && metadata !== null && !("commentKind" in metadata);
905
- const metadataWithKind = shouldTagCommandResponse ? { ...metadata, commentKind: options?.commentKind } : metadata;
906
- const { header, jsonPretty } = this._createMetadataContent(context, metadataWithKind);
309
+ _createCommentBody(context2, message, options) {
310
+ const { metadata, logMessage } = this._processMessage(context2, message);
311
+ const { header, jsonPretty } = this._createMetadataContent(context2, metadata);
907
312
  const metadataContent = this._formatMetadataContent(logMessage, header, jsonPretty);
908
313
  return `${options?.raw ? logMessage?.raw : logMessage?.diff}
909
314
 
910
315
  ${metadataContent}
911
316
  `;
912
317
  }
913
- async postComment(context, message, options = { updateComment: true, raw: false }) {
914
- await this._applyCommandResponsePolicy(context);
915
- const issueContext = this._extractIssueContext(context);
318
+ async postComment(context2, message, options = { updateComment: true, raw: false }) {
319
+ const issueContext = this._extractIssueContext(context2);
916
320
  if (!issueContext) {
917
- context.logger.warn("Cannot post comment: missing issue context in payload");
321
+ context2.logger.info("Cannot post comment: missing issue context in payload");
918
322
  return null;
919
323
  }
920
- const shouldTagCommandResponse = this._shouldApplyCommandResponsePolicy(context);
921
- const body = this._createCommentBody(context, message, {
922
- ...options,
923
- commentKind: options.commentKind ?? (shouldTagCommandResponse ? COMMAND_RESPONSE_KIND : void 0)
924
- });
324
+ const body = this._createCommentBody(context2, message, options);
925
325
  const { issueNumber, commentId, owner, repo } = issueContext;
926
326
  const params = { owner, repo, body, issueNumber };
927
327
  if (options.updateComment) {
928
- if (this._lastCommentId.issueCommentId && !("pull_request" in context.payload && "comment" in context.payload)) {
929
- return this._updateIssueComment(context, params);
328
+ if (this._lastCommentId.issueCommentId && !("pull_request" in context2.payload && "comment" in context2.payload)) {
329
+ return this._updateIssueComment(context2, params);
930
330
  }
931
- if (this._lastCommentId.reviewCommentId && "pull_request" in context.payload && "comment" in context.payload) {
932
- return this._updateReviewComment(context, params);
331
+ if (this._lastCommentId.reviewCommentId && "pull_request" in context2.payload && "comment" in context2.payload) {
332
+ return this._updateReviewComment(context2, params);
933
333
  }
934
334
  }
935
- return this._createNewComment(context, { ...params, commentId });
335
+ return this._createNewComment(context2, { ...params, commentId });
936
336
  }
937
337
  };
938
338
 
339
+ // src/error.ts
340
+ var import_ubiquity_os_logger2 = require("@ubiquity-os/ubiquity-os-logger");
341
+ function transformError(context2, error) {
342
+ let loggerError;
343
+ if (error instanceof AggregateError) {
344
+ loggerError = context2.logger.error(
345
+ error.errors.map((err) => {
346
+ if (err instanceof import_ubiquity_os_logger2.LogReturn) {
347
+ return err.logMessage.raw;
348
+ } else if (err instanceof Error) {
349
+ return err.message;
350
+ } else {
351
+ return err;
352
+ }
353
+ }).join("\n\n"),
354
+ { error }
355
+ );
356
+ } else if (error instanceof Error || error instanceof import_ubiquity_os_logger2.LogReturn) {
357
+ loggerError = error;
358
+ } else {
359
+ loggerError = context2.logger.error(String(error));
360
+ }
361
+ return loggerError;
362
+ }
363
+
939
364
  // src/helpers/command.ts
940
365
  var import_value = require("@sinclair/typebox/value");
941
366
  function getCommand(inputs, pluginOptions) {
@@ -968,169 +393,7 @@ function decompressString(compressed) {
968
393
 
969
394
  // src/octokit.ts
970
395
  var import_core = require("@octokit/core");
971
-
972
- // ../../node_modules/@octokit/plugin-paginate-graphql/dist-bundle/index.js
973
- var generateMessage = (path, cursorValue) => `The cursor at "${path.join(
974
- ","
975
- )}" did not change its value "${cursorValue}" after a page transition. Please make sure your that your query is set up correctly.`;
976
- var MissingCursorChange = class extends Error {
977
- constructor(pageInfo, cursorValue) {
978
- super(generateMessage(pageInfo.pathInQuery, cursorValue));
979
- this.pageInfo = pageInfo;
980
- this.cursorValue = cursorValue;
981
- if (Error.captureStackTrace) {
982
- Error.captureStackTrace(this, this.constructor);
983
- }
984
- }
985
- name = "MissingCursorChangeError";
986
- };
987
- var MissingPageInfo = class extends Error {
988
- constructor(response) {
989
- super(
990
- `No pageInfo property found in response. Please make sure to specify the pageInfo in your query. Response-Data: ${JSON.stringify(
991
- response,
992
- null,
993
- 2
994
- )}`
995
- );
996
- this.response = response;
997
- if (Error.captureStackTrace) {
998
- Error.captureStackTrace(this, this.constructor);
999
- }
1000
- }
1001
- name = "MissingPageInfo";
1002
- };
1003
- var isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
1004
- function findPaginatedResourcePath(responseData) {
1005
- const paginatedResourcePath = deepFindPathToProperty(
1006
- responseData,
1007
- "pageInfo"
1008
- );
1009
- if (paginatedResourcePath.length === 0) {
1010
- throw new MissingPageInfo(responseData);
1011
- }
1012
- return paginatedResourcePath;
1013
- }
1014
- var deepFindPathToProperty = (object, searchProp, path = []) => {
1015
- for (const key of Object.keys(object)) {
1016
- const currentPath = [...path, key];
1017
- const currentValue = object[key];
1018
- if (isObject(currentValue)) {
1019
- if (currentValue.hasOwnProperty(searchProp)) {
1020
- return currentPath;
1021
- }
1022
- const result = deepFindPathToProperty(
1023
- currentValue,
1024
- searchProp,
1025
- currentPath
1026
- );
1027
- if (result.length > 0) {
1028
- return result;
1029
- }
1030
- }
1031
- }
1032
- return [];
1033
- };
1034
- var get = (object, path) => {
1035
- return path.reduce((current, nextProperty) => current[nextProperty], object);
1036
- };
1037
- var set = (object, path, mutator) => {
1038
- const lastProperty = path[path.length - 1];
1039
- const parentPath = [...path].slice(0, -1);
1040
- const parent = get(object, parentPath);
1041
- if (typeof mutator === "function") {
1042
- parent[lastProperty] = mutator(parent[lastProperty]);
1043
- } else {
1044
- parent[lastProperty] = mutator;
1045
- }
1046
- };
1047
- var extractPageInfos = (responseData) => {
1048
- const pageInfoPath = findPaginatedResourcePath(responseData);
1049
- return {
1050
- pathInQuery: pageInfoPath,
1051
- pageInfo: get(responseData, [...pageInfoPath, "pageInfo"])
1052
- };
1053
- };
1054
- var isForwardSearch = (givenPageInfo) => {
1055
- return givenPageInfo.hasOwnProperty("hasNextPage");
1056
- };
1057
- var getCursorFrom = (pageInfo) => isForwardSearch(pageInfo) ? pageInfo.endCursor : pageInfo.startCursor;
1058
- var hasAnotherPage = (pageInfo) => isForwardSearch(pageInfo) ? pageInfo.hasNextPage : pageInfo.hasPreviousPage;
1059
- var createIterator = (octokit) => {
1060
- return (query, initialParameters = {}) => {
1061
- let nextPageExists = true;
1062
- let parameters = { ...initialParameters };
1063
- return {
1064
- [Symbol.asyncIterator]: () => ({
1065
- async next() {
1066
- if (!nextPageExists) return { done: true, value: {} };
1067
- const response = await octokit.graphql(
1068
- query,
1069
- parameters
1070
- );
1071
- const pageInfoContext = extractPageInfos(response);
1072
- const nextCursorValue = getCursorFrom(pageInfoContext.pageInfo);
1073
- nextPageExists = hasAnotherPage(pageInfoContext.pageInfo);
1074
- if (nextPageExists && nextCursorValue === parameters.cursor) {
1075
- throw new MissingCursorChange(pageInfoContext, nextCursorValue);
1076
- }
1077
- parameters = {
1078
- ...parameters,
1079
- cursor: nextCursorValue
1080
- };
1081
- return { done: false, value: response };
1082
- }
1083
- })
1084
- };
1085
- };
1086
- };
1087
- var mergeResponses = (response1, response2) => {
1088
- if (Object.keys(response1).length === 0) {
1089
- return Object.assign(response1, response2);
1090
- }
1091
- const path = findPaginatedResourcePath(response1);
1092
- const nodesPath = [...path, "nodes"];
1093
- const newNodes = get(response2, nodesPath);
1094
- if (newNodes) {
1095
- set(response1, nodesPath, (values) => {
1096
- return [...values, ...newNodes];
1097
- });
1098
- }
1099
- const edgesPath = [...path, "edges"];
1100
- const newEdges = get(response2, edgesPath);
1101
- if (newEdges) {
1102
- set(response1, edgesPath, (values) => {
1103
- return [...values, ...newEdges];
1104
- });
1105
- }
1106
- const pageInfoPath = [...path, "pageInfo"];
1107
- set(response1, pageInfoPath, get(response2, pageInfoPath));
1108
- return response1;
1109
- };
1110
- var createPaginate = (octokit) => {
1111
- const iterator = createIterator(octokit);
1112
- return async (query, initialParameters = {}) => {
1113
- let mergedResponse = {};
1114
- for await (const response of iterator(
1115
- query,
1116
- initialParameters
1117
- )) {
1118
- mergedResponse = mergeResponses(mergedResponse, response);
1119
- }
1120
- return mergedResponse;
1121
- };
1122
- };
1123
- function paginateGraphQL(octokit) {
1124
- return {
1125
- graphql: Object.assign(octokit.graphql, {
1126
- paginate: Object.assign(createPaginate(octokit), {
1127
- iterator: createIterator(octokit)
1128
- })
1129
- })
1130
- };
1131
- }
1132
-
1133
- // src/octokit.ts
396
+ var import_plugin_paginate_graphql = require("@octokit/plugin-paginate-graphql");
1134
397
  var import_plugin_paginate_rest = require("@octokit/plugin-paginate-rest");
1135
398
  var import_plugin_rest_endpoint_methods = require("@octokit/plugin-rest-endpoint-methods");
1136
399
  var import_plugin_retry = require("@octokit/plugin-retry");
@@ -1151,7 +414,7 @@ var defaultOptions = {
1151
414
  }
1152
415
  }
1153
416
  };
1154
- var customOctokit = import_core.Octokit.plugin(import_plugin_throttling.throttling, import_plugin_retry.retry, import_plugin_paginate_rest.paginateRest, import_plugin_rest_endpoint_methods.restEndpointMethods, paginateGraphQL).defaults((instanceOptions) => {
417
+ var customOctokit = import_core.Octokit.plugin(import_plugin_throttling.throttling, import_plugin_retry.retry, import_plugin_paginate_rest.paginateRest, import_plugin_rest_endpoint_methods.restEndpointMethods, import_plugin_paginate_graphql.paginateGraphQL).defaults((instanceOptions) => {
1155
418
  return { ...defaultOptions, ...instanceOptions };
1156
419
  });
1157
420
 
@@ -1168,7 +431,7 @@ async function verifySignature(publicKeyPem, inputs, signature) {
1168
431
  ref: inputs.ref,
1169
432
  command: inputs.command
1170
433
  };
1171
- const pemContents = publicKeyPem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replace(/\s+/g, "");
434
+ const pemContents = publicKeyPem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").trim();
1172
435
  const binaryDer = Uint8Array.from(atob(pemContents), (c) => c.charCodeAt(0));
1173
436
  const publicKey = await crypto.subtle.importKey(
1174
437
  "spki",
@@ -1220,13 +483,16 @@ var inputSchema = import_typebox3.Type.Object({
1220
483
  });
1221
484
 
1222
485
  // src/actions.ts
1223
- (0, import_dotenv.config)();
1224
- async function handleError(context, pluginOptions, error) {
486
+ async function handleError(context2, pluginOptions, error) {
1225
487
  console.error(error);
1226
- const loggerError = transformError(context, error);
1227
- core.setFailed(loggerError.logMessage.diff);
488
+ const loggerError = transformError(context2, error);
489
+ if (loggerError instanceof import_ubiquity_os_logger3.LogReturn) {
490
+ core.setFailed(loggerError.logMessage.diff);
491
+ } else if (loggerError instanceof Error) {
492
+ core.setFailed(loggerError);
493
+ }
1228
494
  if (pluginOptions.postCommentOnError && loggerError) {
1229
- await context.commentHandler.postComment(context, loggerError);
495
+ await context2.commentHandler.postComment(context2, loggerError);
1230
496
  }
1231
497
  }
1232
498
  async function createActionsPlugin(handler, options) {
@@ -1236,8 +502,7 @@ async function createActionsPlugin(handler, options) {
1236
502
  core.setFailed("Error: PLUGIN_GITHUB_TOKEN env is not set");
1237
503
  return;
1238
504
  }
1239
- const githubContext = getGithubContext();
1240
- const body = githubContext.payload.inputs;
505
+ const body = github2.context.payload.inputs;
1241
506
  const inputSchemaErrors = [...import_value3.Value.Errors(inputSchema, body)];
1242
507
  if (inputSchemaErrors.length) {
1243
508
  console.dir(inputSchemaErrors, { depth: null });
@@ -1250,59 +515,58 @@ async function createActionsPlugin(handler, options) {
1250
515
  return;
1251
516
  }
1252
517
  const inputs = import_value3.Value.Decode(inputSchema, body);
1253
- let config2;
518
+ let config;
1254
519
  if (pluginOptions.settingsSchema) {
1255
520
  try {
1256
- config2 = import_value3.Value.Decode(pluginOptions.settingsSchema, import_value3.Value.Default(pluginOptions.settingsSchema, inputs.settings));
521
+ config = import_value3.Value.Decode(pluginOptions.settingsSchema, import_value3.Value.Default(pluginOptions.settingsSchema, inputs.settings));
1257
522
  } catch (e) {
1258
523
  console.dir(...import_value3.Value.Errors(pluginOptions.settingsSchema, inputs.settings), { depth: null });
1259
524
  core.setFailed(`Error: Invalid settings provided.`);
1260
525
  throw e;
1261
526
  }
1262
527
  } else {
1263
- config2 = inputs.settings;
528
+ config = inputs.settings;
1264
529
  }
1265
- let env2;
530
+ let env;
1266
531
  if (pluginOptions.envSchema) {
1267
532
  try {
1268
- env2 = import_value3.Value.Decode(pluginOptions.envSchema, import_value3.Value.Default(pluginOptions.envSchema, process.env));
533
+ env = import_value3.Value.Decode(pluginOptions.envSchema, import_value3.Value.Default(pluginOptions.envSchema, process.env));
1269
534
  } catch (e) {
1270
535
  console.dir(...import_value3.Value.Errors(pluginOptions.envSchema, process.env), { depth: null });
1271
536
  core.setFailed(`Error: Invalid environment provided.`);
1272
537
  throw e;
1273
538
  }
1274
539
  } else {
1275
- env2 = process.env;
540
+ env = process.env;
1276
541
  }
1277
542
  const command = getCommand(inputs, pluginOptions);
1278
- const context = {
543
+ const context2 = {
1279
544
  eventName: inputs.eventName,
1280
545
  payload: inputs.eventPayload,
1281
546
  command,
1282
547
  authToken: inputs.authToken,
1283
548
  ubiquityKernelToken: inputs.ubiquityKernelToken,
1284
549
  octokit: new customOctokit({ auth: inputs.authToken }),
1285
- config: config2,
1286
- env: env2,
1287
- logger: new Logs(pluginOptions.logLevel),
550
+ config,
551
+ env,
552
+ logger: new import_ubiquity_os_logger3.Logs(pluginOptions.logLevel),
1288
553
  commentHandler: new CommentHandler()
1289
554
  };
1290
555
  try {
1291
- const result = await handler(context);
556
+ const result = await handler(context2);
1292
557
  core.setOutput("result", result);
1293
558
  if (pluginOptions?.returnDataToKernel) {
1294
559
  await returnDataToKernel(pluginGithubToken, inputs.stateId, result);
1295
560
  }
1296
561
  } catch (error) {
1297
- await handleError(context, pluginOptions, error);
562
+ await handleError(context2, pluginOptions, error);
1298
563
  }
1299
564
  }
1300
565
  async function returnDataToKernel(repoToken, stateId, output) {
1301
- const githubContext = getGithubContext();
1302
566
  const octokit = new customOctokit({ auth: repoToken });
1303
567
  await octokit.rest.repos.createDispatchEvent({
1304
- owner: githubContext.repo.owner,
1305
- repo: githubContext.repo.repo,
568
+ owner: github2.context.repo.owner,
569
+ repo: github2.context.repo.repo,
1306
570
  event_type: "return-data-to-ubiquity-os-kernel",
1307
571
  client_payload: {
1308
572
  state_id: stateId,
@@ -1319,12 +583,12 @@ function cleanMarkdown(md, options = {}) {
1319
583
  const segments = [];
1320
584
  let lastIndex = 0;
1321
585
  const matches = [...md.matchAll(codeBlockRegex)];
1322
- for (const match2 of matches) {
1323
- if (match2.index > lastIndex) {
1324
- segments.push(processSegment(md.slice(lastIndex, match2.index), tags, shouldCollapseEmptyLines));
586
+ for (const match of matches) {
587
+ if (match.index > lastIndex) {
588
+ segments.push(processSegment(md.slice(lastIndex, match.index), tags, shouldCollapseEmptyLines));
1325
589
  }
1326
- segments.push(match2[0]);
1327
- lastIndex = match2.index + match2[0].length;
590
+ segments.push(match[0]);
591
+ lastIndex = match.index + match[0].length;
1328
592
  }
1329
593
  if (lastIndex < md.length) {
1330
594
  segments.push(processSegment(md.slice(lastIndex), tags, shouldCollapseEmptyLines));
@@ -1339,9 +603,9 @@ function processSegment(segment, extraTags, shouldCollapseEmptyLines) {
1339
603
  return `__INLINE_CODE_${inlineCodes.length - 1}__`;
1340
604
  });
1341
605
  s = s.replace(/<!--[\s\S]*?-->/g, "");
1342
- for (const raw2 of extraTags) {
1343
- if (!raw2) continue;
1344
- const tag = raw2.toLowerCase().trim().replace(/[^\w:-]/g, "");
606
+ for (const raw of extraTags) {
607
+ if (!raw) continue;
608
+ const tag = raw.toLowerCase().trim().replace(/[^\w:-]/g, "");
1345
609
  if (!tag) continue;
1346
610
  if (VOID_TAGS.has(tag)) {
1347
611
  const voidRe = new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi");
@@ -1364,2330 +628,178 @@ function processSegment(segment, extraTags, shouldCollapseEmptyLines) {
1364
628
  return s;
1365
629
  }
1366
630
 
1367
- // src/server.ts
1368
- var import_value4 = require("@sinclair/typebox/value");
1369
-
1370
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/compose.js
1371
- var compose = (middleware, onError, onNotFound) => {
1372
- return (context, next) => {
1373
- let index = -1;
1374
- return dispatch(0);
1375
- async function dispatch(i) {
1376
- if (i <= index) {
1377
- throw new Error("next() called multiple times");
1378
- }
1379
- index = i;
1380
- let res;
1381
- let isError = false;
1382
- let handler;
1383
- if (middleware[i]) {
1384
- handler = middleware[i][0][0];
1385
- context.req.routeIndex = i;
1386
- } else {
1387
- handler = i === middleware.length && next || void 0;
1388
- }
1389
- if (handler) {
1390
- try {
1391
- res = await handler(context, () => dispatch(i + 1));
1392
- } catch (err) {
1393
- if (err instanceof Error && onError) {
1394
- context.error = err;
1395
- res = await onError(err, context);
1396
- isError = true;
1397
- } else {
1398
- throw err;
1399
- }
1400
- }
1401
- } else {
1402
- if (context.finalized === false && onNotFound) {
1403
- res = await onNotFound(context);
1404
- }
1405
- }
1406
- if (res && (context.finalized === false || isError)) {
1407
- context.res = res;
1408
- }
1409
- return context;
1410
- }
1411
- };
1412
- };
1413
-
1414
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/http-exception.js
1415
- var HTTPException = class extends Error {
1416
- res;
1417
- status;
1418
- /**
1419
- * Creates an instance of `HTTPException`.
1420
- * @param status - HTTP status code for the exception. Defaults to 500.
1421
- * @param options - Additional options for the exception.
1422
- */
1423
- constructor(status = 500, options) {
1424
- super(options?.message, { cause: options?.cause });
1425
- this.res = options?.res;
1426
- this.status = status;
631
+ // src/llm/index.ts
632
+ function normalizeBaseUrl(baseUrl) {
633
+ let normalized = baseUrl.trim();
634
+ while (normalized.endsWith("/")) {
635
+ normalized = normalized.slice(0, -1);
1427
636
  }
1428
- /**
1429
- * Returns the response object associated with the exception.
1430
- * If a response object is not provided, a new response is created with the error message and status code.
1431
- * @returns The response object.
1432
- */
1433
- getResponse() {
1434
- if (this.res) {
1435
- const newResponse = new Response(this.res.body, {
1436
- status: this.status,
1437
- headers: this.res.headers
1438
- });
1439
- return newResponse;
1440
- }
1441
- return new Response(this.message, {
1442
- status: this.status
1443
- });
637
+ return normalized;
638
+ }
639
+ function getEnvString(name) {
640
+ if (typeof process === "undefined" || !process?.env) return "";
641
+ return String(process.env[name] ?? "").trim();
642
+ }
643
+ function getAiBaseUrl(options) {
644
+ if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
645
+ return normalizeBaseUrl(options.baseUrl);
1444
646
  }
1445
- };
1446
-
1447
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/request/constants.js
1448
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
1449
-
1450
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/utils/body.js
1451
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
1452
- const { all = false, dot = false } = options;
1453
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
1454
- const contentType = headers.get("Content-Type");
1455
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
1456
- return parseFormData(request, { all, dot });
647
+ const envBaseUrl = getEnvString("UBQ_AI_BASE_URL") || getEnvString("UBQ_AI_URL");
648
+ if (envBaseUrl) return normalizeBaseUrl(envBaseUrl);
649
+ return "https://ai.ubq.fi";
650
+ }
651
+ async function callLlm(options, input) {
652
+ const inputPayload = input;
653
+ const authToken = inputPayload.authToken;
654
+ const ubiquityKernelToken = inputPayload.ubiquityKernelToken;
655
+ const payload = inputPayload.payload ?? inputPayload.eventPayload;
656
+ const owner = payload?.repository?.owner?.login ?? "";
657
+ const repo = payload?.repository?.name ?? "";
658
+ const installationId = payload?.installation?.id;
659
+ if (!authToken) throw new Error("Missing authToken in inputs");
660
+ const isKernelTokenRequired = authToken.trim().startsWith("gh");
661
+ if (isKernelTokenRequired && !ubiquityKernelToken) {
662
+ throw new Error("Missing ubiquityKernelToken in inputs (kernel attestation is required for GitHub auth)");
1457
663
  }
1458
- return {};
1459
- };
1460
- async function parseFormData(request, options) {
1461
- const formData = await request.formData();
1462
- if (formData) {
1463
- return convertFormDataToBodyData(formData, options);
664
+ const { baseUrl, model, stream: isStream, messages, ...rest } = options;
665
+ const url = `${getAiBaseUrl({ ...options, baseUrl })}/v1/chat/completions`;
666
+ const body = JSON.stringify({
667
+ ...rest,
668
+ ...model ? { model } : {},
669
+ messages,
670
+ stream: isStream ?? false
671
+ });
672
+ const headers = {
673
+ Authorization: `Bearer ${authToken}`,
674
+ "Content-Type": "application/json"
675
+ };
676
+ if (owner) headers["X-GitHub-Owner"] = owner;
677
+ if (repo) headers["X-GitHub-Repo"] = repo;
678
+ if (typeof installationId === "number" && Number.isFinite(installationId)) {
679
+ headers["X-GitHub-Installation-Id"] = String(installationId);
1464
680
  }
1465
- return {};
1466
- }
1467
- function convertFormDataToBodyData(formData, options) {
1468
- const form = /* @__PURE__ */ Object.create(null);
1469
- formData.forEach((value, key) => {
1470
- const shouldParseAllValues = options.all || key.endsWith("[]");
1471
- if (!shouldParseAllValues) {
1472
- form[key] = value;
1473
- } else {
1474
- handleParsingAllValues(form, key, value);
681
+ if (ubiquityKernelToken) {
682
+ headers["X-Ubiquity-Kernel-Token"] = ubiquityKernelToken;
683
+ }
684
+ const response = await fetch(url, { method: "POST", headers, body });
685
+ if (!response.ok) {
686
+ const err = await response.text();
687
+ throw new Error(`LLM API error: ${response.status} - ${err}`);
688
+ }
689
+ if (isStream) {
690
+ if (!response.body) {
691
+ throw new Error("LLM API error: missing response body for streaming request");
1475
692
  }
1476
- });
1477
- if (options.dot) {
1478
- Object.entries(form).forEach(([key, value]) => {
1479
- const shouldParseDotValues = key.includes(".");
1480
- if (shouldParseDotValues) {
1481
- handleParsingNestedValues(form, key, value);
1482
- delete form[key];
1483
- }
1484
- });
693
+ return parseSseStream(response.body);
1485
694
  }
1486
- return form;
695
+ return response.json();
1487
696
  }
1488
- var handleParsingAllValues = (form, key, value) => {
1489
- if (form[key] !== void 0) {
1490
- if (Array.isArray(form[key])) {
1491
- ;
1492
- form[key].push(value);
1493
- } else {
1494
- form[key] = [form[key], value];
1495
- }
1496
- } else {
1497
- if (!key.endsWith("[]")) {
1498
- form[key] = value;
1499
- } else {
1500
- form[key] = [value];
1501
- }
1502
- }
1503
- };
1504
- var handleParsingNestedValues = (form, key, value) => {
1505
- let nestedForm = form;
1506
- const keys = key.split(".");
1507
- keys.forEach((key2, index) => {
1508
- if (index === keys.length - 1) {
1509
- nestedForm[key2] = value;
1510
- } else {
1511
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
1512
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
1513
- }
1514
- nestedForm = nestedForm[key2];
1515
- }
1516
- });
1517
- };
1518
-
1519
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/utils/url.js
1520
- var splitPath = (path) => {
1521
- const paths = path.split("/");
1522
- if (paths[0] === "") {
1523
- paths.shift();
1524
- }
1525
- return paths;
1526
- };
1527
- var splitRoutingPath = (routePath) => {
1528
- const { groups, path } = extractGroupsFromPath(routePath);
1529
- const paths = splitPath(path);
1530
- return replaceGroupMarks(paths, groups);
1531
- };
1532
- var extractGroupsFromPath = (path) => {
1533
- const groups = [];
1534
- path = path.replace(/\{[^}]+\}/g, (match2, index) => {
1535
- const mark = `@${index}`;
1536
- groups.push([mark, match2]);
1537
- return mark;
1538
- });
1539
- return { groups, path };
1540
- };
1541
- var replaceGroupMarks = (paths, groups) => {
1542
- for (let i = groups.length - 1; i >= 0; i--) {
1543
- const [mark] = groups[i];
1544
- for (let j = paths.length - 1; j >= 0; j--) {
1545
- if (paths[j].includes(mark)) {
1546
- paths[j] = paths[j].replace(mark, groups[i][1]);
1547
- break;
1548
- }
1549
- }
1550
- }
1551
- return paths;
1552
- };
1553
- var patternCache = {};
1554
- var getPattern = (label, next) => {
1555
- if (label === "*") {
1556
- return "*";
1557
- }
1558
- const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1559
- if (match2) {
1560
- const cacheKey = `${label}#${next}`;
1561
- if (!patternCache[cacheKey]) {
1562
- if (match2[2]) {
1563
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
1564
- } else {
1565
- patternCache[cacheKey] = [label, match2[1], true];
1566
- }
1567
- }
1568
- return patternCache[cacheKey];
1569
- }
1570
- return null;
1571
- };
1572
- var tryDecode = (str, decoder) => {
697
+ async function* parseSseStream(body) {
698
+ const reader = body.getReader();
699
+ const decoder = new TextDecoder();
700
+ let buffer = "";
1573
701
  try {
1574
- return decoder(str);
1575
- } catch {
1576
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
1577
- try {
1578
- return decoder(match2);
1579
- } catch {
1580
- return match2;
1581
- }
1582
- });
1583
- }
1584
- };
1585
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
1586
- var getPath = (request) => {
1587
- const url = request.url;
1588
- const start = url.indexOf("/", url.indexOf(":") + 4);
1589
- let i = start;
1590
- for (; i < url.length; i++) {
1591
- const charCode = url.charCodeAt(i);
1592
- if (charCode === 37) {
1593
- const queryIndex = url.indexOf("?", i);
1594
- const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
1595
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
1596
- } else if (charCode === 63) {
1597
- break;
1598
- }
1599
- }
1600
- return url.slice(start, i);
1601
- };
1602
- var getPathNoStrict = (request) => {
1603
- const result = getPath(request);
1604
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
1605
- };
1606
- var mergePath = (base, sub, ...rest) => {
1607
- if (rest.length) {
1608
- sub = mergePath(sub, ...rest);
1609
- }
1610
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
1611
- };
1612
- var checkOptionalParameter = (path) => {
1613
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
1614
- return null;
1615
- }
1616
- const segments = path.split("/");
1617
- const results = [];
1618
- let basePath = "";
1619
- segments.forEach((segment) => {
1620
- if (segment !== "" && !/\:/.test(segment)) {
1621
- basePath += "/" + segment;
1622
- } else if (/\:/.test(segment)) {
1623
- if (/\?/.test(segment)) {
1624
- if (results.length === 0 && basePath === "") {
1625
- results.push("/");
1626
- } else {
1627
- results.push(basePath);
1628
- }
1629
- const optionalSegment = segment.replace("?", "");
1630
- basePath += "/" + optionalSegment;
1631
- results.push(basePath);
1632
- } else {
1633
- basePath += "/" + segment;
1634
- }
1635
- }
1636
- });
1637
- return results.filter((v, i, a) => a.indexOf(v) === i);
1638
- };
1639
- var _decodeURI = (value) => {
1640
- if (!/[%+]/.test(value)) {
1641
- return value;
1642
- }
1643
- if (value.indexOf("+") !== -1) {
1644
- value = value.replace(/\+/g, " ");
1645
- }
1646
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1647
- };
1648
- var _getQueryParam = (url, key, multiple) => {
1649
- let encoded;
1650
- if (!multiple && key && !/[%+]/.test(key)) {
1651
- let keyIndex2 = url.indexOf("?", 8);
1652
- if (keyIndex2 === -1) {
1653
- return void 0;
1654
- }
1655
- if (!url.startsWith(key, keyIndex2 + 1)) {
1656
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1657
- }
1658
- while (keyIndex2 !== -1) {
1659
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1660
- if (trailingKeyCode === 61) {
1661
- const valueIndex = keyIndex2 + key.length + 2;
1662
- const endIndex = url.indexOf("&", valueIndex);
1663
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1664
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1665
- return "";
1666
- }
1667
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1668
- }
1669
- encoded = /[%+]/.test(url);
1670
- if (!encoded) {
1671
- return void 0;
1672
- }
1673
- }
1674
- const results = {};
1675
- encoded ??= /[%+]/.test(url);
1676
- let keyIndex = url.indexOf("?", 8);
1677
- while (keyIndex !== -1) {
1678
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1679
- let valueIndex = url.indexOf("=", keyIndex);
1680
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1681
- valueIndex = -1;
1682
- }
1683
- let name = url.slice(
1684
- keyIndex + 1,
1685
- valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1686
- );
1687
- if (encoded) {
1688
- name = _decodeURI(name);
1689
- }
1690
- keyIndex = nextKeyIndex;
1691
- if (name === "") {
1692
- continue;
1693
- }
1694
- let value;
1695
- if (valueIndex === -1) {
1696
- value = "";
1697
- } else {
1698
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1699
- if (encoded) {
1700
- value = _decodeURI(value);
1701
- }
1702
- }
1703
- if (multiple) {
1704
- if (!(results[name] && Array.isArray(results[name]))) {
1705
- results[name] = [];
1706
- }
1707
- ;
1708
- results[name].push(value);
1709
- } else {
1710
- results[name] ??= value;
1711
- }
1712
- }
1713
- return key ? results[key] : results;
1714
- };
1715
- var getQueryParam = _getQueryParam;
1716
- var getQueryParams = (url, key) => {
1717
- return _getQueryParam(url, key, true);
1718
- };
1719
- var decodeURIComponent_ = decodeURIComponent;
1720
-
1721
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/request.js
1722
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
1723
- var HonoRequest = class {
1724
- /**
1725
- * `.raw` can get the raw Request object.
1726
- *
1727
- * @see {@link https://hono.dev/docs/api/request#raw}
1728
- *
1729
- * @example
1730
- * ```ts
1731
- * // For Cloudflare Workers
1732
- * app.post('/', async (c) => {
1733
- * const metadata = c.req.raw.cf?.hostMetadata?
1734
- * ...
1735
- * })
1736
- * ```
1737
- */
1738
- raw;
1739
- #validatedData;
1740
- // Short name of validatedData
1741
- #matchResult;
1742
- routeIndex = 0;
1743
- /**
1744
- * `.path` can get the pathname of the request.
1745
- *
1746
- * @see {@link https://hono.dev/docs/api/request#path}
1747
- *
1748
- * @example
1749
- * ```ts
1750
- * app.get('/about/me', (c) => {
1751
- * const pathname = c.req.path // `/about/me`
1752
- * })
1753
- * ```
1754
- */
1755
- path;
1756
- bodyCache = {};
1757
- constructor(request, path = "/", matchResult = [[]]) {
1758
- this.raw = request;
1759
- this.path = path;
1760
- this.#matchResult = matchResult;
1761
- this.#validatedData = {};
1762
- }
1763
- param(key) {
1764
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1765
- }
1766
- #getDecodedParam(key) {
1767
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1768
- const param = this.#getParamValue(paramKey);
1769
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1770
- }
1771
- #getAllDecodedParams() {
1772
- const decoded = {};
1773
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1774
- for (const key of keys) {
1775
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1776
- if (value !== void 0) {
1777
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1778
- }
1779
- }
1780
- return decoded;
1781
- }
1782
- #getParamValue(paramKey) {
1783
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1784
- }
1785
- query(key) {
1786
- return getQueryParam(this.url, key);
1787
- }
1788
- queries(key) {
1789
- return getQueryParams(this.url, key);
1790
- }
1791
- header(name) {
1792
- if (name) {
1793
- return this.raw.headers.get(name) ?? void 0;
1794
- }
1795
- const headerData = {};
1796
- this.raw.headers.forEach((value, key) => {
1797
- headerData[key] = value;
1798
- });
1799
- return headerData;
1800
- }
1801
- async parseBody(options) {
1802
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
1803
- }
1804
- #cachedBody = (key) => {
1805
- const { bodyCache, raw: raw2 } = this;
1806
- const cachedBody = bodyCache[key];
1807
- if (cachedBody) {
1808
- return cachedBody;
1809
- }
1810
- const anyCachedKey = Object.keys(bodyCache)[0];
1811
- if (anyCachedKey) {
1812
- return bodyCache[anyCachedKey].then((body) => {
1813
- if (anyCachedKey === "json") {
1814
- body = JSON.stringify(body);
1815
- }
1816
- return new Response(body)[key]();
1817
- });
1818
- }
1819
- return bodyCache[key] = raw2[key]();
1820
- };
1821
- /**
1822
- * `.json()` can parse Request body of type `application/json`
1823
- *
1824
- * @see {@link https://hono.dev/docs/api/request#json}
1825
- *
1826
- * @example
1827
- * ```ts
1828
- * app.post('/entry', async (c) => {
1829
- * const body = await c.req.json()
1830
- * })
1831
- * ```
1832
- */
1833
- json() {
1834
- return this.#cachedBody("text").then((text) => JSON.parse(text));
1835
- }
1836
- /**
1837
- * `.text()` can parse Request body of type `text/plain`
1838
- *
1839
- * @see {@link https://hono.dev/docs/api/request#text}
1840
- *
1841
- * @example
1842
- * ```ts
1843
- * app.post('/entry', async (c) => {
1844
- * const body = await c.req.text()
1845
- * })
1846
- * ```
1847
- */
1848
- text() {
1849
- return this.#cachedBody("text");
1850
- }
1851
- /**
1852
- * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1853
- *
1854
- * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1855
- *
1856
- * @example
1857
- * ```ts
1858
- * app.post('/entry', async (c) => {
1859
- * const body = await c.req.arrayBuffer()
1860
- * })
1861
- * ```
1862
- */
1863
- arrayBuffer() {
1864
- return this.#cachedBody("arrayBuffer");
1865
- }
1866
- /**
1867
- * Parses the request body as a `Blob`.
1868
- * @example
1869
- * ```ts
1870
- * app.post('/entry', async (c) => {
1871
- * const body = await c.req.blob();
1872
- * });
1873
- * ```
1874
- * @see https://hono.dev/docs/api/request#blob
1875
- */
1876
- blob() {
1877
- return this.#cachedBody("blob");
1878
- }
1879
- /**
1880
- * Parses the request body as `FormData`.
1881
- * @example
1882
- * ```ts
1883
- * app.post('/entry', async (c) => {
1884
- * const body = await c.req.formData();
1885
- * });
1886
- * ```
1887
- * @see https://hono.dev/docs/api/request#formdata
1888
- */
1889
- formData() {
1890
- return this.#cachedBody("formData");
1891
- }
1892
- /**
1893
- * Adds validated data to the request.
1894
- *
1895
- * @param target - The target of the validation.
1896
- * @param data - The validated data to add.
1897
- */
1898
- addValidatedData(target, data) {
1899
- this.#validatedData[target] = data;
1900
- }
1901
- valid(target) {
1902
- return this.#validatedData[target];
1903
- }
1904
- /**
1905
- * `.url()` can get the request url strings.
1906
- *
1907
- * @see {@link https://hono.dev/docs/api/request#url}
1908
- *
1909
- * @example
1910
- * ```ts
1911
- * app.get('/about/me', (c) => {
1912
- * const url = c.req.url // `http://localhost:8787/about/me`
1913
- * ...
1914
- * })
1915
- * ```
1916
- */
1917
- get url() {
1918
- return this.raw.url;
1919
- }
1920
- /**
1921
- * `.method()` can get the method name of the request.
1922
- *
1923
- * @see {@link https://hono.dev/docs/api/request#method}
1924
- *
1925
- * @example
1926
- * ```ts
1927
- * app.get('/about/me', (c) => {
1928
- * const method = c.req.method // `GET`
1929
- * })
1930
- * ```
1931
- */
1932
- get method() {
1933
- return this.raw.method;
1934
- }
1935
- get [GET_MATCH_RESULT]() {
1936
- return this.#matchResult;
1937
- }
1938
- /**
1939
- * `.matchedRoutes()` can return a matched route in the handler
1940
- *
1941
- * @deprecated
1942
- *
1943
- * Use matchedRoutes helper defined in "hono/route" instead.
1944
- *
1945
- * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1946
- *
1947
- * @example
1948
- * ```ts
1949
- * app.use('*', async function logger(c, next) {
1950
- * await next()
1951
- * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1952
- * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1953
- * console.log(
1954
- * method,
1955
- * ' ',
1956
- * path,
1957
- * ' '.repeat(Math.max(10 - path.length, 0)),
1958
- * name,
1959
- * i === c.req.routeIndex ? '<- respond from here' : ''
1960
- * )
1961
- * })
1962
- * })
1963
- * ```
1964
- */
1965
- get matchedRoutes() {
1966
- return this.#matchResult[0].map(([[, route]]) => route);
1967
- }
1968
- /**
1969
- * `routePath()` can retrieve the path registered within the handler
1970
- *
1971
- * @deprecated
1972
- *
1973
- * Use routePath helper defined in "hono/route" instead.
1974
- *
1975
- * @see {@link https://hono.dev/docs/api/request#routepath}
1976
- *
1977
- * @example
1978
- * ```ts
1979
- * app.get('/posts/:id', (c) => {
1980
- * return c.json({ path: c.req.routePath })
1981
- * })
1982
- * ```
1983
- */
1984
- get routePath() {
1985
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1986
- }
1987
- };
1988
-
1989
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/utils/html.js
1990
- var HtmlEscapedCallbackPhase = {
1991
- Stringify: 1,
1992
- BeforeStream: 2,
1993
- Stream: 3
1994
- };
1995
- var raw = (value, callbacks) => {
1996
- const escapedString = new String(value);
1997
- escapedString.isEscaped = true;
1998
- escapedString.callbacks = callbacks;
1999
- return escapedString;
2000
- };
2001
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
2002
- if (typeof str === "object" && !(str instanceof String)) {
2003
- if (!(str instanceof Promise)) {
2004
- str = str.toString();
2005
- }
2006
- if (str instanceof Promise) {
2007
- str = await str;
2008
- }
2009
- }
2010
- const callbacks = str.callbacks;
2011
- if (!callbacks?.length) {
2012
- return Promise.resolve(str);
2013
- }
2014
- if (buffer) {
2015
- buffer[0] += str;
2016
- } else {
2017
- buffer = [str];
2018
- }
2019
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
2020
- (res) => Promise.all(
2021
- res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
2022
- ).then(() => buffer[0])
2023
- );
2024
- if (preserveCallbacks) {
2025
- return raw(await resStr, callbacks);
2026
- } else {
2027
- return resStr;
2028
- }
2029
- };
2030
-
2031
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/context.js
2032
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
2033
- var setDefaultContentType = (contentType, headers) => {
2034
- return {
2035
- "Content-Type": contentType,
2036
- ...headers
2037
- };
2038
- };
2039
- var Context = class {
2040
- #rawRequest;
2041
- #req;
2042
- /**
2043
- * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
2044
- *
2045
- * @see {@link https://hono.dev/docs/api/context#env}
2046
- *
2047
- * @example
2048
- * ```ts
2049
- * // Environment object for Cloudflare Workers
2050
- * app.get('*', async c => {
2051
- * const counter = c.env.COUNTER
2052
- * })
2053
- * ```
2054
- */
2055
- env = {};
2056
- #var;
2057
- finalized = false;
2058
- /**
2059
- * `.error` can get the error object from the middleware if the Handler throws an error.
2060
- *
2061
- * @see {@link https://hono.dev/docs/api/context#error}
2062
- *
2063
- * @example
2064
- * ```ts
2065
- * app.use('*', async (c, next) => {
2066
- * await next()
2067
- * if (c.error) {
2068
- * // do something...
2069
- * }
2070
- * })
2071
- * ```
2072
- */
2073
- error;
2074
- #status;
2075
- #executionCtx;
2076
- #res;
2077
- #layout;
2078
- #renderer;
2079
- #notFoundHandler;
2080
- #preparedHeaders;
2081
- #matchResult;
2082
- #path;
2083
- /**
2084
- * Creates an instance of the Context class.
2085
- *
2086
- * @param req - The Request object.
2087
- * @param options - Optional configuration options for the context.
2088
- */
2089
- constructor(req, options) {
2090
- this.#rawRequest = req;
2091
- if (options) {
2092
- this.#executionCtx = options.executionCtx;
2093
- this.env = options.env;
2094
- this.#notFoundHandler = options.notFoundHandler;
2095
- this.#path = options.path;
2096
- this.#matchResult = options.matchResult;
2097
- }
2098
- }
2099
- /**
2100
- * `.req` is the instance of {@link HonoRequest}.
2101
- */
2102
- get req() {
2103
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
2104
- return this.#req;
2105
- }
2106
- /**
2107
- * @see {@link https://hono.dev/docs/api/context#event}
2108
- * The FetchEvent associated with the current request.
2109
- *
2110
- * @throws Will throw an error if the context does not have a FetchEvent.
2111
- */
2112
- get event() {
2113
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
2114
- return this.#executionCtx;
2115
- } else {
2116
- throw Error("This context has no FetchEvent");
2117
- }
2118
- }
2119
- /**
2120
- * @see {@link https://hono.dev/docs/api/context#executionctx}
2121
- * The ExecutionContext associated with the current request.
2122
- *
2123
- * @throws Will throw an error if the context does not have an ExecutionContext.
2124
- */
2125
- get executionCtx() {
2126
- if (this.#executionCtx) {
2127
- return this.#executionCtx;
2128
- } else {
2129
- throw Error("This context has no ExecutionContext");
2130
- }
2131
- }
2132
- /**
2133
- * @see {@link https://hono.dev/docs/api/context#res}
2134
- * The Response object for the current request.
2135
- */
2136
- get res() {
2137
- return this.#res ||= new Response(null, {
2138
- headers: this.#preparedHeaders ??= new Headers()
2139
- });
2140
- }
2141
- /**
2142
- * Sets the Response object for the current request.
2143
- *
2144
- * @param _res - The Response object to set.
2145
- */
2146
- set res(_res) {
2147
- if (this.#res && _res) {
2148
- _res = new Response(_res.body, _res);
2149
- for (const [k, v] of this.#res.headers.entries()) {
2150
- if (k === "content-type") {
2151
- continue;
2152
- }
2153
- if (k === "set-cookie") {
2154
- const cookies = this.#res.headers.getSetCookie();
2155
- _res.headers.delete("set-cookie");
2156
- for (const cookie of cookies) {
2157
- _res.headers.append("set-cookie", cookie);
2158
- }
2159
- } else {
2160
- _res.headers.set(k, v);
2161
- }
2162
- }
2163
- }
2164
- this.#res = _res;
2165
- this.finalized = true;
2166
- }
2167
- /**
2168
- * `.render()` can create a response within a layout.
2169
- *
2170
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
2171
- *
2172
- * @example
2173
- * ```ts
2174
- * app.get('/', (c) => {
2175
- * return c.render('Hello!')
2176
- * })
2177
- * ```
2178
- */
2179
- render = (...args) => {
2180
- this.#renderer ??= (content) => this.html(content);
2181
- return this.#renderer(...args);
2182
- };
2183
- /**
2184
- * Sets the layout for the response.
2185
- *
2186
- * @param layout - The layout to set.
2187
- * @returns The layout function.
2188
- */
2189
- setLayout = (layout) => this.#layout = layout;
2190
- /**
2191
- * Gets the current layout for the response.
2192
- *
2193
- * @returns The current layout function.
2194
- */
2195
- getLayout = () => this.#layout;
2196
- /**
2197
- * `.setRenderer()` can set the layout in the custom middleware.
2198
- *
2199
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
2200
- *
2201
- * @example
2202
- * ```tsx
2203
- * app.use('*', async (c, next) => {
2204
- * c.setRenderer((content) => {
2205
- * return c.html(
2206
- * <html>
2207
- * <body>
2208
- * <p>{content}</p>
2209
- * </body>
2210
- * </html>
2211
- * )
2212
- * })
2213
- * await next()
2214
- * })
2215
- * ```
2216
- */
2217
- setRenderer = (renderer) => {
2218
- this.#renderer = renderer;
2219
- };
2220
- /**
2221
- * `.header()` can set headers.
2222
- *
2223
- * @see {@link https://hono.dev/docs/api/context#header}
2224
- *
2225
- * @example
2226
- * ```ts
2227
- * app.get('/welcome', (c) => {
2228
- * // Set headers
2229
- * c.header('X-Message', 'Hello!')
2230
- * c.header('Content-Type', 'text/plain')
2231
- *
2232
- * return c.body('Thank you for coming')
2233
- * })
2234
- * ```
2235
- */
2236
- header = (name, value, options) => {
2237
- if (this.finalized) {
2238
- this.#res = new Response(this.#res.body, this.#res);
2239
- }
2240
- const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
2241
- if (value === void 0) {
2242
- headers.delete(name);
2243
- } else if (options?.append) {
2244
- headers.append(name, value);
2245
- } else {
2246
- headers.set(name, value);
2247
- }
2248
- };
2249
- status = (status) => {
2250
- this.#status = status;
2251
- };
2252
- /**
2253
- * `.set()` can set the value specified by the key.
2254
- *
2255
- * @see {@link https://hono.dev/docs/api/context#set-get}
2256
- *
2257
- * @example
2258
- * ```ts
2259
- * app.use('*', async (c, next) => {
2260
- * c.set('message', 'Hono is hot!!')
2261
- * await next()
2262
- * })
2263
- * ```
2264
- */
2265
- set = (key, value) => {
2266
- this.#var ??= /* @__PURE__ */ new Map();
2267
- this.#var.set(key, value);
2268
- };
2269
- /**
2270
- * `.get()` can use the value specified by the key.
2271
- *
2272
- * @see {@link https://hono.dev/docs/api/context#set-get}
2273
- *
2274
- * @example
2275
- * ```ts
2276
- * app.get('/', (c) => {
2277
- * const message = c.get('message')
2278
- * return c.text(`The message is "${message}"`)
2279
- * })
2280
- * ```
2281
- */
2282
- get = (key) => {
2283
- return this.#var ? this.#var.get(key) : void 0;
2284
- };
2285
- /**
2286
- * `.var` can access the value of a variable.
2287
- *
2288
- * @see {@link https://hono.dev/docs/api/context#var}
2289
- *
2290
- * @example
2291
- * ```ts
2292
- * const result = c.var.client.oneMethod()
2293
- * ```
2294
- */
2295
- // c.var.propName is a read-only
2296
- get var() {
2297
- if (!this.#var) {
2298
- return {};
2299
- }
2300
- return Object.fromEntries(this.#var);
2301
- }
2302
- #newResponse(data, arg, headers) {
2303
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
2304
- if (typeof arg === "object" && "headers" in arg) {
2305
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
2306
- for (const [key, value] of argHeaders) {
2307
- if (key.toLowerCase() === "set-cookie") {
2308
- responseHeaders.append(key, value);
2309
- } else {
2310
- responseHeaders.set(key, value);
2311
- }
2312
- }
2313
- }
2314
- if (headers) {
2315
- for (const [k, v] of Object.entries(headers)) {
2316
- if (typeof v === "string") {
2317
- responseHeaders.set(k, v);
2318
- } else {
2319
- responseHeaders.delete(k);
2320
- for (const v2 of v) {
2321
- responseHeaders.append(k, v2);
2322
- }
2323
- }
2324
- }
2325
- }
2326
- const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
2327
- return new Response(data, { status, headers: responseHeaders });
2328
- }
2329
- newResponse = (...args) => this.#newResponse(...args);
2330
- /**
2331
- * `.body()` can return the HTTP response.
2332
- * You can set headers with `.header()` and set HTTP status code with `.status`.
2333
- * This can also be set in `.text()`, `.json()` and so on.
2334
- *
2335
- * @see {@link https://hono.dev/docs/api/context#body}
2336
- *
2337
- * @example
2338
- * ```ts
2339
- * app.get('/welcome', (c) => {
2340
- * // Set headers
2341
- * c.header('X-Message', 'Hello!')
2342
- * c.header('Content-Type', 'text/plain')
2343
- * // Set HTTP status code
2344
- * c.status(201)
2345
- *
2346
- * // Return the response body
2347
- * return c.body('Thank you for coming')
2348
- * })
2349
- * ```
2350
- */
2351
- body = (data, arg, headers) => this.#newResponse(data, arg, headers);
2352
- /**
2353
- * `.text()` can render text as `Content-Type:text/plain`.
2354
- *
2355
- * @see {@link https://hono.dev/docs/api/context#text}
2356
- *
2357
- * @example
2358
- * ```ts
2359
- * app.get('/say', (c) => {
2360
- * return c.text('Hello!')
2361
- * })
2362
- * ```
2363
- */
2364
- text = (text, arg, headers) => {
2365
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
2366
- text,
2367
- arg,
2368
- setDefaultContentType(TEXT_PLAIN, headers)
2369
- );
2370
- };
2371
- /**
2372
- * `.json()` can render JSON as `Content-Type:application/json`.
2373
- *
2374
- * @see {@link https://hono.dev/docs/api/context#json}
2375
- *
2376
- * @example
2377
- * ```ts
2378
- * app.get('/api', (c) => {
2379
- * return c.json({ message: 'Hello!' })
2380
- * })
2381
- * ```
2382
- */
2383
- json = (object, arg, headers) => {
2384
- return this.#newResponse(
2385
- JSON.stringify(object),
2386
- arg,
2387
- setDefaultContentType("application/json", headers)
2388
- );
2389
- };
2390
- html = (html, arg, headers) => {
2391
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
2392
- return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
2393
- };
2394
- /**
2395
- * `.redirect()` can Redirect, default status code is 302.
2396
- *
2397
- * @see {@link https://hono.dev/docs/api/context#redirect}
2398
- *
2399
- * @example
2400
- * ```ts
2401
- * app.get('/redirect', (c) => {
2402
- * return c.redirect('/')
2403
- * })
2404
- * app.get('/redirect-permanently', (c) => {
2405
- * return c.redirect('/', 301)
2406
- * })
2407
- * ```
2408
- */
2409
- redirect = (location, status) => {
2410
- const locationString = String(location);
2411
- this.header(
2412
- "Location",
2413
- // Multibyes should be encoded
2414
- // eslint-disable-next-line no-control-regex
2415
- !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
2416
- );
2417
- return this.newResponse(null, status ?? 302);
2418
- };
2419
- /**
2420
- * `.notFound()` can return the Not Found Response.
2421
- *
2422
- * @see {@link https://hono.dev/docs/api/context#notfound}
2423
- *
2424
- * @example
2425
- * ```ts
2426
- * app.get('/notfound', (c) => {
2427
- * return c.notFound()
2428
- * })
2429
- * ```
2430
- */
2431
- notFound = () => {
2432
- this.#notFoundHandler ??= () => new Response();
2433
- return this.#notFoundHandler(this);
2434
- };
2435
- };
2436
-
2437
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router.js
2438
- var METHOD_NAME_ALL = "ALL";
2439
- var METHOD_NAME_ALL_LOWERCASE = "all";
2440
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
2441
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
2442
- var UnsupportedPathError = class extends Error {
2443
- };
2444
-
2445
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/utils/constants.js
2446
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
2447
-
2448
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/hono-base.js
2449
- var notFoundHandler = (c) => {
2450
- return c.text("404 Not Found", 404);
2451
- };
2452
- var errorHandler = (err, c) => {
2453
- if ("getResponse" in err) {
2454
- const res = err.getResponse();
2455
- return c.newResponse(res.body, res);
2456
- }
2457
- console.error(err);
2458
- return c.text("Internal Server Error", 500);
2459
- };
2460
- var Hono = class _Hono {
2461
- get;
2462
- post;
2463
- put;
2464
- delete;
2465
- options;
2466
- patch;
2467
- all;
2468
- on;
2469
- use;
2470
- /*
2471
- This class is like an abstract class and does not have a router.
2472
- To use it, inherit the class and implement router in the constructor.
2473
- */
2474
- router;
2475
- getPath;
2476
- // Cannot use `#` because it requires visibility at JavaScript runtime.
2477
- _basePath = "/";
2478
- #path = "/";
2479
- routes = [];
2480
- constructor(options = {}) {
2481
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
2482
- allMethods.forEach((method) => {
2483
- this[method] = (args1, ...args) => {
2484
- if (typeof args1 === "string") {
2485
- this.#path = args1;
2486
- } else {
2487
- this.#addRoute(method, this.#path, args1);
2488
- }
2489
- args.forEach((handler) => {
2490
- this.#addRoute(method, this.#path, handler);
2491
- });
2492
- return this;
2493
- };
2494
- });
2495
- this.on = (method, path, ...handlers) => {
2496
- for (const p of [path].flat()) {
2497
- this.#path = p;
2498
- for (const m of [method].flat()) {
2499
- handlers.map((handler) => {
2500
- this.#addRoute(m.toUpperCase(), this.#path, handler);
2501
- });
2502
- }
2503
- }
2504
- return this;
2505
- };
2506
- this.use = (arg1, ...handlers) => {
2507
- if (typeof arg1 === "string") {
2508
- this.#path = arg1;
2509
- } else {
2510
- this.#path = "*";
2511
- handlers.unshift(arg1);
2512
- }
2513
- handlers.forEach((handler) => {
2514
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
2515
- });
2516
- return this;
2517
- };
2518
- const { strict, ...optionsWithoutStrict } = options;
2519
- Object.assign(this, optionsWithoutStrict);
2520
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
2521
- }
2522
- #clone() {
2523
- const clone = new _Hono({
2524
- router: this.router,
2525
- getPath: this.getPath
2526
- });
2527
- clone.errorHandler = this.errorHandler;
2528
- clone.#notFoundHandler = this.#notFoundHandler;
2529
- clone.routes = this.routes;
2530
- return clone;
2531
- }
2532
- #notFoundHandler = notFoundHandler;
2533
- // Cannot use `#` because it requires visibility at JavaScript runtime.
2534
- errorHandler = errorHandler;
2535
- /**
2536
- * `.route()` allows grouping other Hono instance in routes.
2537
- *
2538
- * @see {@link https://hono.dev/docs/api/routing#grouping}
2539
- *
2540
- * @param {string} path - base Path
2541
- * @param {Hono} app - other Hono instance
2542
- * @returns {Hono} routed Hono instance
2543
- *
2544
- * @example
2545
- * ```ts
2546
- * const app = new Hono()
2547
- * const app2 = new Hono()
2548
- *
2549
- * app2.get("/user", (c) => c.text("user"))
2550
- * app.route("/api", app2) // GET /api/user
2551
- * ```
2552
- */
2553
- route(path, app) {
2554
- const subApp = this.basePath(path);
2555
- app.routes.map((r) => {
2556
- let handler;
2557
- if (app.errorHandler === errorHandler) {
2558
- handler = r.handler;
2559
- } else {
2560
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
2561
- handler[COMPOSED_HANDLER] = r.handler;
2562
- }
2563
- subApp.#addRoute(r.method, r.path, handler);
2564
- });
2565
- return this;
2566
- }
2567
- /**
2568
- * `.basePath()` allows base paths to be specified.
2569
- *
2570
- * @see {@link https://hono.dev/docs/api/routing#base-path}
2571
- *
2572
- * @param {string} path - base Path
2573
- * @returns {Hono} changed Hono instance
2574
- *
2575
- * @example
2576
- * ```ts
2577
- * const api = new Hono().basePath('/api')
2578
- * ```
2579
- */
2580
- basePath(path) {
2581
- const subApp = this.#clone();
2582
- subApp._basePath = mergePath(this._basePath, path);
2583
- return subApp;
2584
- }
2585
- /**
2586
- * `.onError()` handles an error and returns a customized Response.
2587
- *
2588
- * @see {@link https://hono.dev/docs/api/hono#error-handling}
2589
- *
2590
- * @param {ErrorHandler} handler - request Handler for error
2591
- * @returns {Hono} changed Hono instance
2592
- *
2593
- * @example
2594
- * ```ts
2595
- * app.onError((err, c) => {
2596
- * console.error(`${err}`)
2597
- * return c.text('Custom Error Message', 500)
2598
- * })
2599
- * ```
2600
- */
2601
- onError = (handler) => {
2602
- this.errorHandler = handler;
2603
- return this;
2604
- };
2605
- /**
2606
- * `.notFound()` allows you to customize a Not Found Response.
2607
- *
2608
- * @see {@link https://hono.dev/docs/api/hono#not-found}
2609
- *
2610
- * @param {NotFoundHandler} handler - request handler for not-found
2611
- * @returns {Hono} changed Hono instance
2612
- *
2613
- * @example
2614
- * ```ts
2615
- * app.notFound((c) => {
2616
- * return c.text('Custom 404 Message', 404)
2617
- * })
2618
- * ```
2619
- */
2620
- notFound = (handler) => {
2621
- this.#notFoundHandler = handler;
2622
- return this;
2623
- };
2624
- /**
2625
- * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
2626
- *
2627
- * @see {@link https://hono.dev/docs/api/hono#mount}
2628
- *
2629
- * @param {string} path - base Path
2630
- * @param {Function} applicationHandler - other Request Handler
2631
- * @param {MountOptions} [options] - options of `.mount()`
2632
- * @returns {Hono} mounted Hono instance
2633
- *
2634
- * @example
2635
- * ```ts
2636
- * import { Router as IttyRouter } from 'itty-router'
2637
- * import { Hono } from 'hono'
2638
- * // Create itty-router application
2639
- * const ittyRouter = IttyRouter()
2640
- * // GET /itty-router/hello
2641
- * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
2642
- *
2643
- * const app = new Hono()
2644
- * app.mount('/itty-router', ittyRouter.handle)
2645
- * ```
2646
- *
2647
- * @example
2648
- * ```ts
2649
- * const app = new Hono()
2650
- * // Send the request to another application without modification.
2651
- * app.mount('/app', anotherApp, {
2652
- * replaceRequest: (req) => req,
2653
- * })
2654
- * ```
2655
- */
2656
- mount(path, applicationHandler, options) {
2657
- let replaceRequest;
2658
- let optionHandler;
2659
- if (options) {
2660
- if (typeof options === "function") {
2661
- optionHandler = options;
2662
- } else {
2663
- optionHandler = options.optionHandler;
2664
- if (options.replaceRequest === false) {
2665
- replaceRequest = (request) => request;
2666
- } else {
2667
- replaceRequest = options.replaceRequest;
2668
- }
2669
- }
2670
- }
2671
- const getOptions = optionHandler ? (c) => {
2672
- const options2 = optionHandler(c);
2673
- return Array.isArray(options2) ? options2 : [options2];
2674
- } : (c) => {
2675
- let executionContext = void 0;
2676
- try {
2677
- executionContext = c.executionCtx;
2678
- } catch {
2679
- }
2680
- return [c.env, executionContext];
2681
- };
2682
- replaceRequest ||= (() => {
2683
- const mergedPath = mergePath(this._basePath, path);
2684
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2685
- return (request) => {
2686
- const url = new URL(request.url);
2687
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2688
- return new Request(url, request);
2689
- };
2690
- })();
2691
- const handler = async (c, next) => {
2692
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2693
- if (res) {
2694
- return res;
2695
- }
2696
- await next();
2697
- };
2698
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2699
- return this;
2700
- }
2701
- #addRoute(method, path, handler) {
2702
- method = method.toUpperCase();
2703
- path = mergePath(this._basePath, path);
2704
- const r = { basePath: this._basePath, path, method, handler };
2705
- this.router.add(method, path, [handler, r]);
2706
- this.routes.push(r);
2707
- }
2708
- #handleError(err, c) {
2709
- if (err instanceof Error) {
2710
- return this.errorHandler(err, c);
2711
- }
2712
- throw err;
2713
- }
2714
- #dispatch(request, executionCtx, env2, method) {
2715
- if (method === "HEAD") {
2716
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env2, "GET")))();
2717
- }
2718
- const path = this.getPath(request, { env: env2 });
2719
- const matchResult = this.router.match(method, path);
2720
- const c = new Context(request, {
2721
- path,
2722
- matchResult,
2723
- env: env2,
2724
- executionCtx,
2725
- notFoundHandler: this.#notFoundHandler
2726
- });
2727
- if (matchResult[0].length === 1) {
2728
- let res;
2729
- try {
2730
- res = matchResult[0][0][0][0](c, async () => {
2731
- c.res = await this.#notFoundHandler(c);
2732
- });
2733
- } catch (err) {
2734
- return this.#handleError(err, c);
2735
- }
2736
- return res instanceof Promise ? res.then(
2737
- (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2738
- ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2739
- }
2740
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2741
- return (async () => {
2742
- try {
2743
- const context = await composed(c);
2744
- if (!context.finalized) {
2745
- throw new Error(
2746
- "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2747
- );
2748
- }
2749
- return context.res;
2750
- } catch (err) {
2751
- return this.#handleError(err, c);
2752
- }
2753
- })();
2754
- }
2755
- /**
2756
- * `.fetch()` will be entry point of your app.
2757
- *
2758
- * @see {@link https://hono.dev/docs/api/hono#fetch}
2759
- *
2760
- * @param {Request} request - request Object of request
2761
- * @param {Env} Env - env Object
2762
- * @param {ExecutionContext} - context of execution
2763
- * @returns {Response | Promise<Response>} response of request
2764
- *
2765
- */
2766
- fetch = (request, ...rest) => {
2767
- return this.#dispatch(request, rest[1], rest[0], request.method);
2768
- };
2769
- /**
2770
- * `.request()` is a useful method for testing.
2771
- * You can pass a URL or pathname to send a GET request.
2772
- * app will return a Response object.
2773
- * ```ts
2774
- * test('GET /hello is ok', async () => {
2775
- * const res = await app.request('/hello')
2776
- * expect(res.status).toBe(200)
2777
- * })
2778
- * ```
2779
- * @see https://hono.dev/docs/api/hono#request
2780
- */
2781
- request = (input, requestInit, Env, executionCtx) => {
2782
- if (input instanceof Request) {
2783
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2784
- }
2785
- input = input.toString();
2786
- return this.fetch(
2787
- new Request(
2788
- /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2789
- requestInit
2790
- ),
2791
- Env,
2792
- executionCtx
2793
- );
2794
- };
2795
- /**
2796
- * `.fire()` automatically adds a global fetch event listener.
2797
- * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2798
- * @deprecated
2799
- * Use `fire` from `hono/service-worker` instead.
2800
- * ```ts
2801
- * import { Hono } from 'hono'
2802
- * import { fire } from 'hono/service-worker'
2803
- *
2804
- * const app = new Hono()
2805
- * // ...
2806
- * fire(app)
2807
- * ```
2808
- * @see https://hono.dev/docs/api/hono#fire
2809
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2810
- * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2811
- */
2812
- fire = () => {
2813
- addEventListener("fetch", (event) => {
2814
- event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2815
- });
2816
- };
2817
- };
2818
-
2819
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/matcher.js
2820
- var emptyParam = [];
2821
- function match(method, path) {
2822
- const matchers = this.buildAllMatchers();
2823
- const match2 = ((method2, path2) => {
2824
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2825
- const staticMatch = matcher[2][path2];
2826
- if (staticMatch) {
2827
- return staticMatch;
2828
- }
2829
- const match3 = path2.match(matcher[0]);
2830
- if (!match3) {
2831
- return [[], emptyParam];
2832
- }
2833
- const index = match3.indexOf("", 1);
2834
- return [matcher[1][index], match3];
2835
- });
2836
- this.match = match2;
2837
- return match2(method, path);
2838
- }
2839
-
2840
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/node.js
2841
- var LABEL_REG_EXP_STR = "[^/]+";
2842
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
2843
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2844
- var PATH_ERROR = /* @__PURE__ */ Symbol();
2845
- var regExpMetaChars = new Set(".\\+*[^]$()");
2846
- function compareKey(a, b) {
2847
- if (a.length === 1) {
2848
- return b.length === 1 ? a < b ? -1 : 1 : -1;
2849
- }
2850
- if (b.length === 1) {
2851
- return 1;
2852
- }
2853
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2854
- return 1;
2855
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2856
- return -1;
2857
- }
2858
- if (a === LABEL_REG_EXP_STR) {
2859
- return 1;
2860
- } else if (b === LABEL_REG_EXP_STR) {
2861
- return -1;
2862
- }
2863
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2864
- }
2865
- var Node = class _Node {
2866
- #index;
2867
- #varIndex;
2868
- #children = /* @__PURE__ */ Object.create(null);
2869
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2870
- if (tokens.length === 0) {
2871
- if (this.#index !== void 0) {
2872
- throw PATH_ERROR;
2873
- }
2874
- if (pathErrorCheckOnly) {
2875
- return;
2876
- }
2877
- this.#index = index;
2878
- return;
2879
- }
2880
- const [token, ...restTokens] = tokens;
2881
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2882
- let node;
2883
- if (pattern) {
2884
- const name = pattern[1];
2885
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2886
- if (name && pattern[2]) {
2887
- if (regexpStr === ".*") {
2888
- throw PATH_ERROR;
2889
- }
2890
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2891
- if (/\((?!\?:)/.test(regexpStr)) {
2892
- throw PATH_ERROR;
2893
- }
2894
- }
2895
- node = this.#children[regexpStr];
2896
- if (!node) {
2897
- if (Object.keys(this.#children).some(
2898
- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2899
- )) {
2900
- throw PATH_ERROR;
2901
- }
2902
- if (pathErrorCheckOnly) {
2903
- return;
2904
- }
2905
- node = this.#children[regexpStr] = new _Node();
2906
- if (name !== "") {
2907
- node.#varIndex = context.varIndex++;
2908
- }
2909
- }
2910
- if (!pathErrorCheckOnly && name !== "") {
2911
- paramMap.push([name, node.#varIndex]);
2912
- }
2913
- } else {
2914
- node = this.#children[token];
2915
- if (!node) {
2916
- if (Object.keys(this.#children).some(
2917
- (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2918
- )) {
2919
- throw PATH_ERROR;
2920
- }
2921
- if (pathErrorCheckOnly) {
2922
- return;
2923
- }
2924
- node = this.#children[token] = new _Node();
2925
- }
2926
- }
2927
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2928
- }
2929
- buildRegExpStr() {
2930
- const childKeys = Object.keys(this.#children).sort(compareKey);
2931
- const strList = childKeys.map((k) => {
2932
- const c = this.#children[k];
2933
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2934
- });
2935
- if (typeof this.#index === "number") {
2936
- strList.unshift(`#${this.#index}`);
2937
- }
2938
- if (strList.length === 0) {
2939
- return "";
2940
- }
2941
- if (strList.length === 1) {
2942
- return strList[0];
2943
- }
2944
- return "(?:" + strList.join("|") + ")";
2945
- }
2946
- };
2947
-
2948
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/trie.js
2949
- var Trie = class {
2950
- #context = { varIndex: 0 };
2951
- #root = new Node();
2952
- insert(path, index, pathErrorCheckOnly) {
2953
- const paramAssoc = [];
2954
- const groups = [];
2955
- for (let i = 0; ; ) {
2956
- let replaced = false;
2957
- path = path.replace(/\{[^}]+\}/g, (m) => {
2958
- const mark = `@\\${i}`;
2959
- groups[i] = [mark, m];
2960
- i++;
2961
- replaced = true;
2962
- return mark;
2963
- });
2964
- if (!replaced) {
2965
- break;
2966
- }
2967
- }
2968
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2969
- for (let i = groups.length - 1; i >= 0; i--) {
2970
- const [mark] = groups[i];
2971
- for (let j = tokens.length - 1; j >= 0; j--) {
2972
- if (tokens[j].indexOf(mark) !== -1) {
2973
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
2974
- break;
702
+ while (true) {
703
+ const { value, done: isDone } = await reader.read();
704
+ if (isDone) break;
705
+ buffer += decoder.decode(value, { stream: true });
706
+ const events = buffer.split("\n\n");
707
+ buffer = events.pop() || "";
708
+ for (const event of events) {
709
+ if (event.startsWith("data: ")) {
710
+ const data = event.slice(6);
711
+ if (data === "[DONE]") return;
712
+ yield JSON.parse(data);
2975
713
  }
2976
714
  }
2977
715
  }
2978
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2979
- return paramAssoc;
2980
- }
2981
- buildRegExp() {
2982
- let regexp = this.#root.buildRegExpStr();
2983
- if (regexp === "") {
2984
- return [/^$/, [], []];
2985
- }
2986
- let captureIndex = 0;
2987
- const indexReplacementMap = [];
2988
- const paramReplacementMap = [];
2989
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2990
- if (handlerIndex !== void 0) {
2991
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
2992
- return "$()";
2993
- }
2994
- if (paramIndex !== void 0) {
2995
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2996
- return "";
2997
- }
2998
- return "";
2999
- });
3000
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
3001
- }
3002
- };
3003
-
3004
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/router.js
3005
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
3006
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3007
- function buildWildcardRegExp(path) {
3008
- return wildcardRegExpCache[path] ??= new RegExp(
3009
- path === "*" ? "" : `^${path.replace(
3010
- /\/\*$|([.\\+*[^\]$()])/g,
3011
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
3012
- )}$`
3013
- );
3014
- }
3015
- function clearWildcardRegExpCache() {
3016
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3017
- }
3018
- function buildMatcherFromPreprocessedRoutes(routes) {
3019
- const trie = new Trie();
3020
- const handlerData = [];
3021
- if (routes.length === 0) {
3022
- return nullMatcher;
3023
- }
3024
- const routesWithStaticPathFlag = routes.map(
3025
- (route) => [!/\*|\/:/.test(route[0]), ...route]
3026
- ).sort(
3027
- ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
3028
- );
3029
- const staticMap = /* @__PURE__ */ Object.create(null);
3030
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
3031
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
3032
- if (pathErrorCheckOnly) {
3033
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
3034
- } else {
3035
- j++;
3036
- }
3037
- let paramAssoc;
3038
- try {
3039
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
3040
- } catch (e) {
3041
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
3042
- }
3043
- if (pathErrorCheckOnly) {
3044
- continue;
3045
- }
3046
- handlerData[j] = handlers.map(([h, paramCount]) => {
3047
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
3048
- paramCount -= 1;
3049
- for (; paramCount >= 0; paramCount--) {
3050
- const [key, value] = paramAssoc[paramCount];
3051
- paramIndexMap[key] = value;
3052
- }
3053
- return [h, paramIndexMap];
3054
- });
3055
- }
3056
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
3057
- for (let i = 0, len = handlerData.length; i < len; i++) {
3058
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
3059
- const map = handlerData[i][j]?.[1];
3060
- if (!map) {
3061
- continue;
3062
- }
3063
- const keys = Object.keys(map);
3064
- for (let k = 0, len3 = keys.length; k < len3; k++) {
3065
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
3066
- }
3067
- }
3068
- }
3069
- const handlerMap = [];
3070
- for (const i in indexReplacementMap) {
3071
- handlerMap[i] = handlerData[indexReplacementMap[i]];
3072
- }
3073
- return [regexp, handlerMap, staticMap];
3074
- }
3075
- function findMiddleware(middleware, path) {
3076
- if (!middleware) {
3077
- return void 0;
3078
- }
3079
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
3080
- if (buildWildcardRegExp(k).test(path)) {
3081
- return [...middleware[k]];
3082
- }
716
+ } finally {
717
+ reader.releaseLock();
3083
718
  }
3084
- return void 0;
3085
719
  }
3086
- var RegExpRouter = class {
3087
- name = "RegExpRouter";
3088
- #middleware;
3089
- #routes;
3090
- constructor() {
3091
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3092
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3093
- }
3094
- add(method, path, handler) {
3095
- const middleware = this.#middleware;
3096
- const routes = this.#routes;
3097
- if (!middleware || !routes) {
3098
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3099
- }
3100
- if (!middleware[method]) {
3101
- ;
3102
- [middleware, routes].forEach((handlerMap) => {
3103
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
3104
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
3105
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
3106
- });
3107
- });
3108
- }
3109
- if (path === "/*") {
3110
- path = "*";
3111
- }
3112
- const paramCount = (path.match(/\/:/g) || []).length;
3113
- if (/\*$/.test(path)) {
3114
- const re = buildWildcardRegExp(path);
3115
- if (method === METHOD_NAME_ALL) {
3116
- Object.keys(middleware).forEach((m) => {
3117
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3118
- });
3119
- } else {
3120
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3121
- }
3122
- Object.keys(middleware).forEach((m) => {
3123
- if (method === METHOD_NAME_ALL || method === m) {
3124
- Object.keys(middleware[m]).forEach((p) => {
3125
- re.test(p) && middleware[m][p].push([handler, paramCount]);
3126
- });
3127
- }
3128
- });
3129
- Object.keys(routes).forEach((m) => {
3130
- if (method === METHOD_NAME_ALL || method === m) {
3131
- Object.keys(routes[m]).forEach(
3132
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
3133
- );
3134
- }
3135
- });
3136
- return;
3137
- }
3138
- const paths = checkOptionalParameter(path) || [path];
3139
- for (let i = 0, len = paths.length; i < len; i++) {
3140
- const path2 = paths[i];
3141
- Object.keys(routes).forEach((m) => {
3142
- if (method === METHOD_NAME_ALL || method === m) {
3143
- routes[m][path2] ||= [
3144
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
3145
- ];
3146
- routes[m][path2].push([handler, paramCount - len + i + 1]);
3147
- }
3148
- });
3149
- }
3150
- }
3151
- match = match;
3152
- buildAllMatchers() {
3153
- const matchers = /* @__PURE__ */ Object.create(null);
3154
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
3155
- matchers[method] ||= this.#buildMatcher(method);
3156
- });
3157
- this.#middleware = this.#routes = void 0;
3158
- clearWildcardRegExpCache();
3159
- return matchers;
3160
- }
3161
- #buildMatcher(method) {
3162
- const routes = [];
3163
- let hasOwnRoute = method === METHOD_NAME_ALL;
3164
- [this.#middleware, this.#routes].forEach((r) => {
3165
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
3166
- if (ownRoute.length !== 0) {
3167
- hasOwnRoute ||= true;
3168
- routes.push(...ownRoute);
3169
- } else if (method !== METHOD_NAME_ALL) {
3170
- routes.push(
3171
- ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
3172
- );
3173
- }
3174
- });
3175
- if (!hasOwnRoute) {
3176
- return null;
3177
- } else {
3178
- return buildMatcherFromPreprocessedRoutes(routes);
3179
- }
3180
- }
3181
- };
3182
-
3183
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/smart-router/router.js
3184
- var SmartRouter = class {
3185
- name = "SmartRouter";
3186
- #routers = [];
3187
- #routes = [];
3188
- constructor(init) {
3189
- this.#routers = init.routers;
3190
- }
3191
- add(method, path, handler) {
3192
- if (!this.#routes) {
3193
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3194
- }
3195
- this.#routes.push([method, path, handler]);
3196
- }
3197
- match(method, path) {
3198
- if (!this.#routes) {
3199
- throw new Error("Fatal error");
3200
- }
3201
- const routers = this.#routers;
3202
- const routes = this.#routes;
3203
- const len = routers.length;
3204
- let i = 0;
3205
- let res;
3206
- for (; i < len; i++) {
3207
- const router = routers[i];
3208
- try {
3209
- for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
3210
- router.add(...routes[i2]);
3211
- }
3212
- res = router.match(method, path);
3213
- } catch (e) {
3214
- if (e instanceof UnsupportedPathError) {
3215
- continue;
3216
- }
3217
- throw e;
3218
- }
3219
- this.match = router.match.bind(router);
3220
- this.#routers = [router];
3221
- this.#routes = void 0;
3222
- break;
3223
- }
3224
- if (i === len) {
3225
- throw new Error("Fatal error");
3226
- }
3227
- this.name = `SmartRouter + ${this.activeRouter.name}`;
3228
- return res;
3229
- }
3230
- get activeRouter() {
3231
- if (this.#routes || this.#routers.length !== 1) {
3232
- throw new Error("No active router has been determined yet.");
3233
- }
3234
- return this.#routers[0];
3235
- }
3236
- };
3237
-
3238
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/trie-router/node.js
3239
- var emptyParams = /* @__PURE__ */ Object.create(null);
3240
- var Node2 = class _Node2 {
3241
- #methods;
3242
- #children;
3243
- #patterns;
3244
- #order = 0;
3245
- #params = emptyParams;
3246
- constructor(method, handler, children) {
3247
- this.#children = children || /* @__PURE__ */ Object.create(null);
3248
- this.#methods = [];
3249
- if (method && handler) {
3250
- const m = /* @__PURE__ */ Object.create(null);
3251
- m[method] = { handler, possibleKeys: [], score: 0 };
3252
- this.#methods = [m];
3253
- }
3254
- this.#patterns = [];
3255
- }
3256
- insert(method, path, handler) {
3257
- this.#order = ++this.#order;
3258
- let curNode = this;
3259
- const parts = splitRoutingPath(path);
3260
- const possibleKeys = [];
3261
- for (let i = 0, len = parts.length; i < len; i++) {
3262
- const p = parts[i];
3263
- const nextP = parts[i + 1];
3264
- const pattern = getPattern(p, nextP);
3265
- const key = Array.isArray(pattern) ? pattern[0] : p;
3266
- if (key in curNode.#children) {
3267
- curNode = curNode.#children[key];
3268
- if (pattern) {
3269
- possibleKeys.push(pattern[1]);
3270
- }
3271
- continue;
3272
- }
3273
- curNode.#children[key] = new _Node2();
3274
- if (pattern) {
3275
- curNode.#patterns.push(pattern);
3276
- possibleKeys.push(pattern[1]);
3277
- }
3278
- curNode = curNode.#children[key];
3279
- }
3280
- curNode.#methods.push({
3281
- [method]: {
3282
- handler,
3283
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
3284
- score: this.#order
3285
- }
3286
- });
3287
- return curNode;
3288
- }
3289
- #getHandlerSets(node, method, nodeParams, params) {
3290
- const handlerSets = [];
3291
- for (let i = 0, len = node.#methods.length; i < len; i++) {
3292
- const m = node.#methods[i];
3293
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
3294
- const processedSet = {};
3295
- if (handlerSet !== void 0) {
3296
- handlerSet.params = /* @__PURE__ */ Object.create(null);
3297
- handlerSets.push(handlerSet);
3298
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
3299
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
3300
- const key = handlerSet.possibleKeys[i2];
3301
- const processed = processedSet[handlerSet.score];
3302
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
3303
- processedSet[handlerSet.score] = true;
3304
- }
3305
- }
3306
- }
3307
- }
3308
- return handlerSets;
3309
- }
3310
- search(method, path) {
3311
- const handlerSets = [];
3312
- this.#params = emptyParams;
3313
- const curNode = this;
3314
- let curNodes = [curNode];
3315
- const parts = splitPath(path);
3316
- const curNodesQueue = [];
3317
- for (let i = 0, len = parts.length; i < len; i++) {
3318
- const part = parts[i];
3319
- const isLast = i === len - 1;
3320
- const tempNodes = [];
3321
- for (let j = 0, len2 = curNodes.length; j < len2; j++) {
3322
- const node = curNodes[j];
3323
- const nextNode = node.#children[part];
3324
- if (nextNode) {
3325
- nextNode.#params = node.#params;
3326
- if (isLast) {
3327
- if (nextNode.#children["*"]) {
3328
- handlerSets.push(
3329
- ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
3330
- );
3331
- }
3332
- handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
3333
- } else {
3334
- tempNodes.push(nextNode);
3335
- }
3336
- }
3337
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
3338
- const pattern = node.#patterns[k];
3339
- const params = node.#params === emptyParams ? {} : { ...node.#params };
3340
- if (pattern === "*") {
3341
- const astNode = node.#children["*"];
3342
- if (astNode) {
3343
- handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
3344
- astNode.#params = params;
3345
- tempNodes.push(astNode);
3346
- }
3347
- continue;
3348
- }
3349
- const [key, name, matcher] = pattern;
3350
- if (!part && !(matcher instanceof RegExp)) {
3351
- continue;
3352
- }
3353
- const child = node.#children[key];
3354
- const restPathString = parts.slice(i).join("/");
3355
- if (matcher instanceof RegExp) {
3356
- const m = matcher.exec(restPathString);
3357
- if (m) {
3358
- params[name] = m[0];
3359
- handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
3360
- if (Object.keys(child.#children).length) {
3361
- child.#params = params;
3362
- const componentCount = m[0].match(/\//)?.length ?? 0;
3363
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
3364
- targetCurNodes.push(child);
3365
- }
3366
- continue;
3367
- }
3368
- }
3369
- if (matcher === true || matcher.test(part)) {
3370
- params[name] = part;
3371
- if (isLast) {
3372
- handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
3373
- if (child.#children["*"]) {
3374
- handlerSets.push(
3375
- ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
3376
- );
3377
- }
3378
- } else {
3379
- child.#params = params;
3380
- tempNodes.push(child);
3381
- }
3382
- }
3383
- }
3384
- }
3385
- curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
3386
- }
3387
- if (handlerSets.length > 1) {
3388
- handlerSets.sort((a, b) => {
3389
- return a.score - b.score;
3390
- });
3391
- }
3392
- return [handlerSets.map(({ handler, params }) => [handler, params])];
3393
- }
3394
- };
3395
-
3396
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/router/trie-router/router.js
3397
- var TrieRouter = class {
3398
- name = "TrieRouter";
3399
- #node;
3400
- constructor() {
3401
- this.#node = new Node2();
3402
- }
3403
- add(method, path, handler) {
3404
- const results = checkOptionalParameter(path);
3405
- if (results) {
3406
- for (let i = 0, len = results.length; i < len; i++) {
3407
- this.#node.insert(method, results[i], handler);
3408
- }
3409
- return;
3410
- }
3411
- this.#node.insert(method, path, handler);
3412
- }
3413
- match(method, path) {
3414
- return this.#node.search(method, path);
3415
- }
3416
- };
3417
-
3418
- // ../../node_modules/.deno/hono@4.11.3/node_modules/hono/dist/hono.js
3419
- var Hono2 = class extends Hono {
3420
- /**
3421
- * Creates an instance of the Hono class.
3422
- *
3423
- * @param options - Optional configuration options for the Hono instance.
3424
- */
3425
- constructor(options = {}) {
3426
- super(options);
3427
- this.router = options.router ?? new SmartRouter({
3428
- routers: [new RegExpRouter(), new TrieRouter()]
3429
- });
3430
- }
3431
- };
3432
720
 
3433
721
  // src/server.ts
3434
- async function handleError2(context, pluginOptions, error) {
722
+ var import_value4 = require("@sinclair/typebox/value");
723
+ var import_ubiquity_os_logger4 = require("@ubiquity-os/ubiquity-os-logger");
724
+ var import_hono = require("hono");
725
+ var import_adapter2 = require("hono/adapter");
726
+ var import_http_exception = require("hono/http-exception");
727
+ async function handleError2(context2, pluginOptions, error) {
3435
728
  console.error(error);
3436
- const loggerError = transformError(context, error);
729
+ const loggerError = transformError(context2, error);
3437
730
  if (pluginOptions.postCommentOnError && loggerError) {
3438
- await context.commentHandler.postComment(context, loggerError);
731
+ await context2.commentHandler.postComment(context2, loggerError);
3439
732
  }
3440
- throw new HTTPException(500, { message: "Unexpected error" });
733
+ throw new import_http_exception.HTTPException(500, { message: "Unexpected error" });
3441
734
  }
3442
735
  function createPlugin(handler, manifest, options) {
3443
736
  const pluginOptions = getPluginOptions(options);
3444
- const app = new Hono2();
737
+ const app = new import_hono.Hono();
3445
738
  app.get("/manifest.json", (ctx) => {
3446
739
  return ctx.json(manifest);
3447
740
  });
3448
741
  app.post("/", async function appPost(ctx) {
3449
742
  if (ctx.req.header("content-type") !== "application/json") {
3450
- throw new HTTPException(400, { message: "Content-Type must be application/json" });
743
+ throw new import_http_exception.HTTPException(400, { message: "Content-Type must be application/json" });
3451
744
  }
3452
745
  const body = await ctx.req.json();
3453
746
  const inputSchemaErrors = [...import_value4.Value.Errors(inputSchema, body)];
3454
747
  if (inputSchemaErrors.length) {
3455
748
  console.dir(inputSchemaErrors, { depth: null });
3456
- throw new HTTPException(400, { message: "Invalid body" });
749
+ throw new import_http_exception.HTTPException(400, { message: "Invalid body" });
3457
750
  }
3458
751
  const signature = body.signature;
3459
752
  if (!pluginOptions.bypassSignatureVerification && !await verifySignature(pluginOptions.kernelPublicKey, body, signature)) {
3460
- throw new HTTPException(400, { message: "Invalid signature" });
753
+ throw new import_http_exception.HTTPException(400, { message: "Invalid signature" });
3461
754
  }
3462
755
  const inputs = import_value4.Value.Decode(inputSchema, body);
3463
- let config2;
756
+ let config;
3464
757
  if (pluginOptions.settingsSchema) {
3465
758
  try {
3466
- config2 = import_value4.Value.Decode(pluginOptions.settingsSchema, import_value4.Value.Default(pluginOptions.settingsSchema, inputs.settings));
759
+ config = import_value4.Value.Decode(pluginOptions.settingsSchema, import_value4.Value.Default(pluginOptions.settingsSchema, inputs.settings));
3467
760
  } catch (e) {
3468
761
  console.dir(...import_value4.Value.Errors(pluginOptions.settingsSchema, inputs.settings), { depth: null });
3469
762
  throw e;
3470
763
  }
3471
764
  } else {
3472
- config2 = inputs.settings;
765
+ config = inputs.settings;
3473
766
  }
3474
- let env2;
3475
- const honoEnvironment = env(ctx);
767
+ let env;
768
+ const honoEnvironment = (0, import_adapter2.env)(ctx);
3476
769
  if (pluginOptions.envSchema) {
3477
770
  try {
3478
- env2 = import_value4.Value.Decode(pluginOptions.envSchema, import_value4.Value.Default(pluginOptions.envSchema, honoEnvironment));
771
+ env = import_value4.Value.Decode(pluginOptions.envSchema, import_value4.Value.Default(pluginOptions.envSchema, honoEnvironment));
3479
772
  } catch (e) {
3480
773
  console.dir(...import_value4.Value.Errors(pluginOptions.envSchema, honoEnvironment), { depth: null });
3481
774
  throw e;
3482
775
  }
3483
776
  } else {
3484
- env2 = ctx.env;
777
+ env = ctx.env;
3485
778
  }
3486
779
  const workerName = new URL(inputs.ref).hostname.split(".")[0];
3487
- PluginRuntimeInfo.getInstance({ ...env2, CLOUDFLARE_WORKER_NAME: workerName });
780
+ PluginRuntimeInfo.getInstance({ ...env, CLOUDFLARE_WORKER_NAME: workerName });
3488
781
  const command = getCommand(inputs, pluginOptions);
3489
- const context = {
782
+ const context2 = {
3490
783
  eventName: inputs.eventName,
3491
784
  payload: inputs.eventPayload,
3492
785
  command,
3493
786
  authToken: inputs.authToken,
3494
787
  ubiquityKernelToken: inputs.ubiquityKernelToken,
3495
788
  octokit: new customOctokit({ auth: inputs.authToken }),
3496
- config: config2,
3497
- env: env2,
3498
- logger: new Logs(pluginOptions.logLevel),
789
+ config,
790
+ env,
791
+ logger: new import_ubiquity_os_logger4.Logs(pluginOptions.logLevel),
3499
792
  commentHandler: new CommentHandler()
3500
793
  };
3501
794
  try {
3502
- const result = await handler(context);
795
+ const result = await handler(context2);
3503
796
  return ctx.json({ stateId: inputs.stateId, output: result ?? {} });
3504
797
  } catch (error) {
3505
- await handleError2(context, pluginOptions, error);
798
+ await handleError2(context2, pluginOptions, error);
3506
799
  }
3507
800
  });
3508
801
  return app;
3509
802
  }
3510
-
3511
- // src/llm/index.ts
3512
- var EMPTY_STRING = "";
3513
- function normalizeBaseUrl(baseUrl) {
3514
- let normalized = baseUrl.trim();
3515
- while (normalized.endsWith("/")) {
3516
- normalized = normalized.slice(0, -1);
3517
- }
3518
- return normalized;
3519
- }
3520
- var MAX_LLM_RETRIES = 2;
3521
- var RETRY_BACKOFF_MS = [250, 750];
3522
- function getRetryDelayMs(attempt) {
3523
- return RETRY_BACKOFF_MS[Math.min(attempt, RETRY_BACKOFF_MS.length - 1)] ?? 750;
3524
- }
3525
- function sleep(ms) {
3526
- return new Promise((resolve) => setTimeout(resolve, ms));
3527
- }
3528
- function getEnvString(name) {
3529
- if (typeof process === "undefined" || !process?.env) return EMPTY_STRING;
3530
- return String(process.env[name] ?? EMPTY_STRING).trim();
3531
- }
3532
- function getAiBaseUrl(options) {
3533
- if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
3534
- return normalizeBaseUrl(options.baseUrl);
3535
- }
3536
- const envBaseUrl = getEnvString("UOS_AI_URL") || getEnvString("UOS_AI_BASE_URL");
3537
- if (envBaseUrl) return normalizeBaseUrl(envBaseUrl);
3538
- return "https://ai-ubq-fi.deno.dev";
3539
- }
3540
- async function callLlm(options, input) {
3541
- const authToken = String(input.authToken ?? EMPTY_STRING).trim();
3542
- if (!authToken) {
3543
- const err = new Error("Missing authToken in input");
3544
- err.status = 401;
3545
- throw err;
3546
- }
3547
- const kernelToken = "ubiquityKernelToken" in input ? input.ubiquityKernelToken : void 0;
3548
- const payload = getPayload(input);
3549
- const { owner, repo, installationId } = getRepoMetadata(payload);
3550
- ensureKernelToken(authToken, kernelToken);
3551
- const { baseUrl, model, stream: isStream, messages, ...rest } = options;
3552
- ensureMessages(messages);
3553
- const url = buildAiUrl(options, baseUrl);
3554
- const body = JSON.stringify({
3555
- ...rest,
3556
- ...model ? { model } : {},
3557
- messages,
3558
- stream: isStream ?? false
3559
- });
3560
- const headers = buildHeaders(authToken, {
3561
- owner,
3562
- repo,
3563
- installationId,
3564
- ubiquityKernelToken: kernelToken
3565
- });
3566
- const response = await fetchWithRetry(url, { method: "POST", headers, body }, MAX_LLM_RETRIES);
3567
- if (isStream) {
3568
- if (!response.body) {
3569
- throw new Error("LLM API error: missing response body for streaming request");
3570
- }
3571
- return parseSseStream(response.body);
3572
- }
3573
- return response.json();
3574
- }
3575
- function ensureKernelToken(authToken, kernelToken) {
3576
- const isKernelTokenRequired = authToken.startsWith("gh");
3577
- if (isKernelTokenRequired && !kernelToken) {
3578
- const err = new Error("Missing ubiquityKernelToken in input (kernel attestation is required for GitHub auth)");
3579
- err.status = 401;
3580
- throw err;
3581
- }
3582
- }
3583
- function ensureMessages(messages) {
3584
- if (!Array.isArray(messages) || messages.length === 0) {
3585
- const err = new Error("messages must be a non-empty array");
3586
- err.status = 400;
3587
- throw err;
3588
- }
3589
- }
3590
- function buildAiUrl(options, baseUrl) {
3591
- return `${getAiBaseUrl({ ...options, baseUrl })}/v1/chat/completions`;
3592
- }
3593
- async function fetchWithRetry(url, options, maxRetries) {
3594
- let attempt = 0;
3595
- let lastError;
3596
- while (attempt <= maxRetries) {
3597
- try {
3598
- const response = await fetch(url, options);
3599
- if (response.ok) return response;
3600
- const errText = await response.text();
3601
- if (response.status >= 500 && attempt < maxRetries) {
3602
- await sleep(getRetryDelayMs(attempt));
3603
- attempt += 1;
3604
- continue;
3605
- }
3606
- const error = new Error(`LLM API error: ${response.status} - ${errText}`);
3607
- error.status = response.status;
3608
- throw error;
3609
- } catch (error) {
3610
- lastError = error;
3611
- if (attempt >= maxRetries) throw error;
3612
- await sleep(getRetryDelayMs(attempt));
3613
- attempt += 1;
3614
- }
3615
- }
3616
- throw lastError ?? new Error("LLM API error: request failed after retries");
3617
- }
3618
- function getPayload(input) {
3619
- if ("payload" in input) {
3620
- return input.payload;
3621
- }
3622
- return input.eventPayload;
3623
- }
3624
- function getRepoMetadata(payload) {
3625
- const repoPayload = payload;
3626
- return {
3627
- owner: repoPayload?.repository?.owner?.login ?? EMPTY_STRING,
3628
- repo: repoPayload?.repository?.name ?? EMPTY_STRING,
3629
- installationId: repoPayload?.installation?.id
3630
- };
3631
- }
3632
- function buildHeaders(authToken, options) {
3633
- const headers = {
3634
- Authorization: `Bearer ${authToken}`,
3635
- "Content-Type": "application/json"
3636
- };
3637
- if (options.owner) headers["X-GitHub-Owner"] = options.owner;
3638
- if (options.repo) headers["X-GitHub-Repo"] = options.repo;
3639
- if (typeof options.installationId === "number" && Number.isFinite(options.installationId)) {
3640
- headers["X-GitHub-Installation-Id"] = String(options.installationId);
3641
- }
3642
- if (options.ubiquityKernelToken) {
3643
- headers["X-Ubiquity-Kernel-Token"] = options.ubiquityKernelToken;
3644
- }
3645
- return headers;
3646
- }
3647
- async function* parseSseStream(body) {
3648
- const reader = body.getReader();
3649
- const decoder = new TextDecoder();
3650
- let buffer = EMPTY_STRING;
3651
- try {
3652
- while (true) {
3653
- const { value, done: isDone } = await reader.read();
3654
- if (isDone) break;
3655
- buffer += decoder.decode(value, { stream: true });
3656
- const { events, remainder } = splitSseEvents(buffer);
3657
- buffer = remainder;
3658
- for (const event of events) {
3659
- const data = getEventData(event);
3660
- if (!data) continue;
3661
- if (data.trim() === "[DONE]") return;
3662
- yield parseEventData(data);
3663
- }
3664
- }
3665
- } finally {
3666
- reader.releaseLock();
3667
- }
3668
- }
3669
- function splitSseEvents(buffer) {
3670
- const normalized = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3671
- const parts = normalized.split("\n\n");
3672
- const remainder = parts.pop() ?? EMPTY_STRING;
3673
- return { events: parts, remainder };
3674
- }
3675
- function getEventData(event) {
3676
- if (!event.trim()) return null;
3677
- const dataLines = event.split("\n").filter((line) => line.startsWith("data:"));
3678
- if (!dataLines.length) return null;
3679
- const data = dataLines.map((line) => line.startsWith("data: ") ? line.slice(6) : line.slice(5).replace(/^ /, EMPTY_STRING)).join("\n");
3680
- return data || null;
3681
- }
3682
- function parseEventData(data) {
3683
- try {
3684
- return JSON.parse(data);
3685
- } catch (error) {
3686
- const message = error instanceof Error ? error.message : String(error);
3687
- const preview = data.length > 200 ? `${data.slice(0, 200)}...` : data;
3688
- throw new Error(`LLM stream parse error: ${message}. Data: ${preview}`);
3689
- }
3690
- }
3691
803
  // Annotate the CommonJS export names for ESM import in node:
3692
804
  0 && (module.exports = {
3693
805
  CommentHandler,