@kodycodes/cli 3.35.7 → 3.35.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +4 -1
  2. package/dist/{auth-I4A4RTE7.js → auth-GBBIWKPB.js} +6 -6
  3. package/dist/bin.js +7 -7
  4. package/dist/{chunk-X5L5M6AR.js → chunk-6JQXFR73.js} +11 -1
  5. package/dist/{chunk-X5L5M6AR.js.map → chunk-6JQXFR73.js.map} +1 -1
  6. package/dist/{chunk-F4HCZY5C.js → chunk-ABFH2TJY.js} +6 -6
  7. package/dist/{chunk-GSYTEGUY.js → chunk-BOMZNZB2.js} +4 -4
  8. package/dist/{chunk-X3MVBUHJ.js → chunk-COQHFREF.js} +6 -5
  9. package/dist/chunk-COQHFREF.js.map +6 -0
  10. package/dist/{chunk-XFFHQPOG.js → chunk-E6EIOEB5.js} +42 -40
  11. package/dist/{chunk-XFFHQPOG.js.map → chunk-E6EIOEB5.js.map} +1 -1
  12. package/dist/{chunk-F5DCN33G.js → chunk-HCDO2RMN.js} +2 -2
  13. package/dist/{chunk-UNRRMZM2.js → chunk-HL6FD7UL.js} +2 -2
  14. package/dist/{chunk-DDSBBCN6.js → chunk-HNLC2H7W.js} +3 -3
  15. package/dist/{chunk-WEKG36KS.js → chunk-JNBDH4NY.js} +2 -2
  16. package/dist/{chunk-UIW3FXV5.js → chunk-MU2WOVN7.js} +7 -4
  17. package/dist/chunk-MU2WOVN7.js.map +6 -0
  18. package/dist/{chunk-7GKOFBH2.js → chunk-RIUEXR4R.js} +5 -5
  19. package/dist/{chunk-3UTX2E3H.js → chunk-UXEHBZMM.js} +2 -2
  20. package/dist/{chunk-3UTX2E3H.js.map → chunk-UXEHBZMM.js.map} +1 -1
  21. package/dist/{chunk-KFQOJ2LQ.js → chunk-UZS6F24U.js} +3 -3
  22. package/dist/cli-credential.d.ts +4 -0
  23. package/dist/cli.js +7 -7
  24. package/dist/{commands-2LL5NA6U.js → commands-ANISA5GD.js} +2 -2
  25. package/dist/{dev-command-37Y4LPMT.js → dev-command-HAYADKYA.js} +10 -10
  26. package/dist/{git-credential-VW5TSHI5.js → git-credential-IHTFM5PZ.js} +7 -7
  27. package/dist/{local-execute-RIAZOGMB.js → local-execute-PAJFQIOW.js} +6 -6
  28. package/dist/{local-package-graph-I5QAE63V.js → local-package-graph-UWXHNF54.js} +5 -5
  29. package/dist/{local-package-run-4UEU5MZ3.js → local-package-run-SUXJXOQ5.js} +9 -9
  30. package/dist/{local-secrets-D3DDO34G.js → local-secrets-WHO57JNS.js} +5 -5
  31. package/dist/{mock-dep-resolve-N4QP5UPG.js → mock-dep-resolve-VIQ7GIDE.js} +4 -4
  32. package/dist/{mock-local-deps-F4QO5VS2.js → mock-local-deps-BQRCZA2U.js} +6 -6
  33. package/dist/{open-api-client-PNMMTIVA.js → open-api-client-O7SH6HJK.js} +5 -5
  34. package/dist/publish-builder.js +916 -801
  35. package/dist/{publish-offload-RHDNOZRY.js → publish-offload-3PVUD3SK.js} +2 -2
  36. package/dist/{remote-execute-VJNJDZNR.js → remote-execute-RLVZLLNH.js} +5 -5
  37. package/dist/{run-executor-4EL6ZFDN.js → run-executor-OTDXG3EY.js} +2 -2
  38. package/dist/{setup-git-2K3LNZDO.js → setup-git-Y723F7WP.js} +6 -6
  39. package/dist/{whoami-6DU33ZVG.js → whoami-L6GNUTV6.js} +4 -4
  40. package/package.json +1 -1
  41. package/dist/chunk-UIW3FXV5.js.map +0 -6
  42. package/dist/chunk-X3MVBUHJ.js.map +0 -6
  43. /package/dist/{auth-I4A4RTE7.js.map → auth-GBBIWKPB.js.map} +0 -0
  44. /package/dist/{chunk-F4HCZY5C.js.map → chunk-ABFH2TJY.js.map} +0 -0
  45. /package/dist/{chunk-GSYTEGUY.js.map → chunk-BOMZNZB2.js.map} +0 -0
  46. /package/dist/{chunk-F5DCN33G.js.map → chunk-HCDO2RMN.js.map} +0 -0
  47. /package/dist/{chunk-UNRRMZM2.js.map → chunk-HL6FD7UL.js.map} +0 -0
  48. /package/dist/{chunk-DDSBBCN6.js.map → chunk-HNLC2H7W.js.map} +0 -0
  49. /package/dist/{chunk-WEKG36KS.js.map → chunk-JNBDH4NY.js.map} +0 -0
  50. /package/dist/{chunk-7GKOFBH2.js.map → chunk-RIUEXR4R.js.map} +0 -0
  51. /package/dist/{chunk-KFQOJ2LQ.js.map → chunk-UZS6F24U.js.map} +0 -0
  52. /package/dist/{commands-2LL5NA6U.js.map → commands-ANISA5GD.js.map} +0 -0
  53. /package/dist/{dev-command-37Y4LPMT.js.map → dev-command-HAYADKYA.js.map} +0 -0
  54. /package/dist/{git-credential-VW5TSHI5.js.map → git-credential-IHTFM5PZ.js.map} +0 -0
  55. /package/dist/{local-execute-RIAZOGMB.js.map → local-execute-PAJFQIOW.js.map} +0 -0
  56. /package/dist/{local-package-graph-I5QAE63V.js.map → local-package-graph-UWXHNF54.js.map} +0 -0
  57. /package/dist/{local-package-run-4UEU5MZ3.js.map → local-package-run-SUXJXOQ5.js.map} +0 -0
  58. /package/dist/{local-secrets-D3DDO34G.js.map → local-secrets-WHO57JNS.js.map} +0 -0
  59. /package/dist/{mock-dep-resolve-N4QP5UPG.js.map → mock-dep-resolve-VIQ7GIDE.js.map} +0 -0
  60. /package/dist/{mock-local-deps-F4QO5VS2.js.map → mock-local-deps-BQRCZA2U.js.map} +0 -0
  61. /package/dist/{open-api-client-PNMMTIVA.js.map → open-api-client-O7SH6HJK.js.map} +0 -0
  62. /package/dist/{publish-offload-RHDNOZRY.js.map → publish-offload-3PVUD3SK.js.map} +0 -0
  63. /package/dist/{remote-execute-VJNJDZNR.js.map → remote-execute-RLVZLLNH.js.map} +0 -0
  64. /package/dist/{run-executor-4EL6ZFDN.js.map → run-executor-OTDXG3EY.js.map} +0 -0
  65. /package/dist/{setup-git-2K3LNZDO.js.map → setup-git-Y723F7WP.js.map} +0 -0
  66. /package/dist/{whoami-6DU33ZVG.js.map → whoami-L6GNUTV6.js.map} +0 -0
@@ -131,6 +131,7 @@ function mapRow(row) {
131
131
  entryPoint: String(row["entry_point"]),
132
132
  kvKey: String(row["kv_key"]),
133
133
  dependenciesJson: String(row["dependencies_json"] ?? "[]"),
134
+ totalBytes: typeof row["total_bytes"] === "number" ? row["total_bytes"] : null,
134
135
  createdAt: String(row["created_at"]),
135
136
  updatedAt: String(row["updated_at"])
136
137
  };
@@ -273,8 +274,9 @@ function prepareUnguardedInsert(db, input3, id, now) {
273
274
  return db.prepare(
274
275
  `INSERT INTO published_bundle_artifacts (
275
276
  id, user_id, source_id, published_commit, artifact_kind, artifact_name,
276
- entry_point, kv_key, dependencies_json, created_at, updated_at
277
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
277
+ entry_point, kv_key, dependencies_json, total_bytes, created_at,
278
+ updated_at
279
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
278
280
  ).bind(
279
281
  id,
280
282
  input3.userId,
@@ -285,6 +287,7 @@ function prepareUnguardedInsert(db, input3, id, now) {
285
287
  input3.entryPoint,
286
288
  input3.kvKey,
287
289
  input3.dependenciesJson,
290
+ input3.totalBytes ?? null,
288
291
  now,
289
292
  now
290
293
  );
@@ -293,9 +296,10 @@ function prepareGuardedInsert(db, input3, id, now) {
293
296
  return db.prepare(
294
297
  `INSERT INTO published_bundle_artifacts (
295
298
  id, user_id, source_id, published_commit, artifact_kind, artifact_name,
296
- entry_point, kv_key, dependencies_json, created_at, updated_at
299
+ entry_point, kv_key, dependencies_json, total_bytes, created_at,
300
+ updated_at
297
301
  )
298
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
302
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
299
303
  WHERE EXISTS (
300
304
  SELECT 1 FROM entity_sources
301
305
  WHERE id = ?
@@ -313,6 +317,7 @@ function prepareGuardedInsert(db, input3, id, now) {
313
317
  input3.entryPoint,
314
318
  input3.kvKey,
315
319
  input3.dependenciesJson,
320
+ input3.totalBytes ?? null,
316
321
  now,
317
322
  now,
318
323
  input3.sourceId,
@@ -325,7 +330,7 @@ function prepareUnguardedUpdate(db, input3, now) {
325
330
  `UPDATE published_bundle_artifacts
326
331
  SET user_id = ?, source_id = ?, published_commit = ?, artifact_kind = ?,
327
332
  artifact_name = ?, entry_point = ?, kv_key = ?, dependencies_json = ?,
328
- updated_at = ?
333
+ total_bytes = ?, updated_at = ?
329
334
  WHERE id = ?`
330
335
  ).bind(
331
336
  input3.userId,
@@ -336,6 +341,7 @@ function prepareUnguardedUpdate(db, input3, now) {
336
341
  input3.entryPoint,
337
342
  input3.kvKey,
338
343
  input3.dependenciesJson,
344
+ input3.totalBytes ?? null,
339
345
  now,
340
346
  input3.id
341
347
  );
@@ -345,7 +351,7 @@ function prepareGuardedUpdate(db, input3, now) {
345
351
  `UPDATE published_bundle_artifacts
346
352
  SET user_id = ?, source_id = ?, published_commit = ?, artifact_kind = ?,
347
353
  artifact_name = ?, entry_point = ?, kv_key = ?, dependencies_json = ?,
348
- updated_at = ?
354
+ total_bytes = ?, updated_at = ?
349
355
  WHERE id = ?
350
356
  AND EXISTS (
351
357
  SELECT 1 FROM entity_sources
@@ -363,6 +369,7 @@ function prepareGuardedUpdate(db, input3, now) {
363
369
  input3.entryPoint,
364
370
  input3.kvKey,
365
371
  input3.dependenciesJson,
372
+ input3.totalBytes ?? null,
366
373
  now,
367
374
  input3.id,
368
375
  input3.sourceId,
@@ -26413,640 +26420,6 @@ var init_package_artifact_targets = __esm({
26413
26420
  }
26414
26421
  });
26415
26422
 
26416
- // ../worker/src/package-runtime/module-graph-path-basics.ts
26417
- function joinPath(...parts) {
26418
- return parts.join("/").replace(/\/+/g, "/").replace(/\/\.\//g, "/");
26419
- }
26420
- function dirname(filePath) {
26421
- const normalized = filePath.replace(/\/+/g, "/");
26422
- const separator = normalized.lastIndexOf("/");
26423
- return separator === -1 ? "." : normalized.slice(0, separator) || ".";
26424
- }
26425
- function relativePath(fromDir, toPath) {
26426
- const fromParts = fromDir.split("/").filter(Boolean);
26427
- const toParts = toPath.split("/").filter(Boolean);
26428
- let sharedIndex = 0;
26429
- while (sharedIndex < fromParts.length && sharedIndex < toParts.length && fromParts[sharedIndex] === toParts[sharedIndex]) {
26430
- sharedIndex += 1;
26431
- }
26432
- const upward = fromParts.slice(sharedIndex).map(() => "..");
26433
- const downward = toParts.slice(sharedIndex);
26434
- return [...upward, ...downward].join("/");
26435
- }
26436
- function createRelativeImportSpecifier(fromPath, targetPath) {
26437
- const fromDir = dirname(fromPath);
26438
- const relative = relativePath(fromDir, targetPath);
26439
- const normalized = relative === "." || relative.startsWith("./") || relative.startsWith("../") ? relative : `./${relative}`;
26440
- return normalized.replaceAll("\\", "/");
26441
- }
26442
- function normalizeWorkspaceModulePath(path) {
26443
- const parts = [];
26444
- for (const segment of path.replace(/\\/g, "/").split("/")) {
26445
- if (!segment || segment === ".") continue;
26446
- if (segment === "..") {
26447
- parts.pop();
26448
- continue;
26449
- }
26450
- parts.push(segment);
26451
- }
26452
- return parts.join("/");
26453
- }
26454
- var runtimeModulePath;
26455
- var init_module_graph_path_basics = __esm({
26456
- "../worker/src/package-runtime/module-graph-path-basics.ts"() {
26457
- "use strict";
26458
- runtimeModulePath = ".__kody_virtual__/runtime.js";
26459
- }
26460
- });
26461
-
26462
- // ../worker/src/package-runtime/published-source-dependencies.ts
26463
- function getDeclaredPackageDependencies(sourceFiles) {
26464
- const packageJson = sourceFiles[packageManifestPath2];
26465
- if (!packageJson) return [];
26466
- try {
26467
- const parsed = JSON.parse(packageJson);
26468
- return Object.keys(parsed.dependencies ?? {}).sort(
26469
- (left, right) => left.localeCompare(right)
26470
- );
26471
- } catch {
26472
- return [];
26473
- }
26474
- }
26475
- function getMissingInstalledDependencies(input3) {
26476
- return input3.dependencies.filter(
26477
- (dependencyName) => input3.sourceFiles[`node_modules/${dependencyName}/package.json`] == null
26478
- );
26479
- }
26480
- function listMissingPublishedSourceInstalledDependencies(sourceFiles) {
26481
- const dependencies = getDeclaredPackageDependencies(sourceFiles);
26482
- if (dependencies.length === 0) return [];
26483
- return getMissingInstalledDependencies({
26484
- sourceFiles,
26485
- dependencies
26486
- });
26487
- }
26488
- function createPublishedRuntimeBundleMissingError(input3) {
26489
- return new Error(
26490
- `${input3.bundleLabel} declares npm dependencies (${input3.missingDependencies.map((dependency) => `"${dependency}"`).join(
26491
- ", "
26492
- )}) but ${publishedRuntimeBundleMissingMessage}. Republish the package so Kody can install dependencies and persist a fresh runtime bundle artifact.`
26493
- );
26494
- }
26495
- function assertPublishedSourceCanRebuildWithoutInstallingDeps(input3) {
26496
- const missingDependencies = listMissingPublishedSourceInstalledDependencies(
26497
- input3.sourceFiles
26498
- );
26499
- if (missingDependencies.length === 0) return;
26500
- throw createPublishedRuntimeBundleMissingError({
26501
- missingDependencies,
26502
- bundleLabel: input3.bundleLabel
26503
- });
26504
- }
26505
- var packageManifestPath2, publishedRuntimeBundleMissingMessage, publishedNpmBundleRebuildWindowMs;
26506
- var init_published_source_dependencies = __esm({
26507
- "../worker/src/package-runtime/published-source-dependencies.ts"() {
26508
- "use strict";
26509
- packageManifestPath2 = "package.json";
26510
- publishedRuntimeBundleMissingMessage = "no published runtime bundle artifact is available yet";
26511
- publishedNpmBundleRebuildWindowMs = 2 * 60 * 1e3;
26512
- }
26513
- });
26514
-
26515
- // ../worker/src/package-runtime/rewrite-local-execute-secret-fetch.ts
26516
- function collectTopLevelFetchCollisionNames(source) {
26517
- if (!source.trim()) return /* @__PURE__ */ new Set();
26518
- try {
26519
- const parsed = parseModuleSource(source);
26520
- const program = parsed.program;
26521
- const body = program?.body ?? parsed.body;
26522
- if (!Array.isArray(body)) return /* @__PURE__ */ new Set();
26523
- const names = /* @__PURE__ */ new Set();
26524
- for (const statement of body) {
26525
- if (!statement || typeof statement !== "object") continue;
26526
- const node2 = statement;
26527
- if (node2.type === "ImportDeclaration") {
26528
- for (const specifier of node2.specifiers ?? []) {
26529
- const local = getBindingIdentifierName(
26530
- specifier.local
26531
- );
26532
- if (local) names.add(local);
26533
- }
26534
- continue;
26535
- }
26536
- if (node2.type === "FunctionDeclaration" || node2.type === "ClassDeclaration") {
26537
- const name = getBindingIdentifierName(node2.id);
26538
- if (name) names.add(name);
26539
- continue;
26540
- }
26541
- if (node2.type === "VariableDeclaration") {
26542
- for (const declarator of node2.declarations ?? []) {
26543
- collectPatternBoundNames(declarator.id, names);
26544
- }
26545
- continue;
26546
- }
26547
- if (node2.type === "ExportNamedDeclaration" && node2.declaration) {
26548
- const declaration = node2.declaration;
26549
- if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
26550
- const name = getBindingIdentifierName(
26551
- declaration.id
26552
- );
26553
- if (name) names.add(name);
26554
- continue;
26555
- }
26556
- if (declaration.type === "VariableDeclaration") {
26557
- for (const declarator of declaration.declarations ?? []) {
26558
- collectPatternBoundNames(declarator.id, names);
26559
- }
26560
- }
26561
- }
26562
- }
26563
- return names;
26564
- } catch {
26565
- return null;
26566
- }
26567
- }
26568
- function getBindingIdentifierName(node2) {
26569
- if (!node2 || typeof node2 !== "object") return null;
26570
- const typed = node2;
26571
- if (typed.type !== "Identifier" || typeof typed.name !== "string") return null;
26572
- return typed.name;
26573
- }
26574
- function collectPatternBoundNames(node2, names) {
26575
- if (!node2 || typeof node2 !== "object") return;
26576
- const typed = node2;
26577
- switch (typed.type) {
26578
- case "Identifier": {
26579
- const name = getBindingIdentifierName(typed);
26580
- if (name) names.add(name);
26581
- return;
26582
- }
26583
- case "ObjectPattern": {
26584
- for (const property of typed.properties ?? []) {
26585
- if (!property || typeof property !== "object") continue;
26586
- const prop = property;
26587
- if (prop.type === "RestElement") {
26588
- collectPatternBoundNames(prop.argument, names);
26589
- continue;
26590
- }
26591
- if (prop.type === "ObjectProperty" || prop.type === "Property") {
26592
- collectPatternBoundNames(prop.value, names);
26593
- }
26594
- }
26595
- return;
26596
- }
26597
- case "ArrayPattern": {
26598
- for (const element of typed.elements ?? []) {
26599
- collectPatternBoundNames(element, names);
26600
- }
26601
- return;
26602
- }
26603
- case "AssignmentPattern": {
26604
- collectPatternBoundNames(typed.left, names);
26605
- return;
26606
- }
26607
- case "RestElement": {
26608
- collectPatternBoundNames(typed.argument, names);
26609
- return;
26610
- }
26611
- default:
26612
- return;
26613
- }
26614
- }
26615
- var init_rewrite_local_execute_secret_fetch = __esm({
26616
- "../worker/src/package-runtime/rewrite-local-execute-secret-fetch.ts"() {
26617
- "use strict";
26618
- init_module_source();
26619
- init_module_graph_path_basics();
26620
- }
26621
- });
26622
-
26623
- // ../worker/src/kody-evaluate-bindings.ts
26624
- var kodyCallDispatcherName;
26625
- var init_kody_evaluate_bindings = __esm({
26626
- "../worker/src/kody-evaluate-bindings.ts"() {
26627
- "use strict";
26628
- kodyCallDispatcherName = "__kodyCallDispatcher";
26629
- }
26630
- });
26631
-
26632
- // ../worker/src/mcp/secrets/placeholders.ts
26633
- var init_placeholders = __esm({
26634
- "../worker/src/mcp/secrets/placeholders.ts"() {
26635
- "use strict";
26636
- }
26637
- });
26638
-
26639
- // ../worker/src/mcp/execute-modules/integration-host-allowlist.ts
26640
- var init_integration_host_allowlist = __esm({
26641
- "../worker/src/mcp/execute-modules/integration-host-allowlist.ts"() {
26642
- "use strict";
26643
- }
26644
- });
26645
-
26646
- // ../worker/src/mcp/execute-modules/kody-runtime-utils.ts
26647
- function createExecuteHelperPrelude() {
26648
- return `
26649
- class IntegrationHostNotAllowedError extends Error {
26650
- constructor(integrationName, disallowedHost) {
26651
- super(
26652
- \`Integration "\${integrationName}" does not allow requests to host "\${disallowedHost}". \` +
26653
- \`The host must be listed in the integration's requiredHosts or match its apiBaseUrl.\`
26654
- );
26655
- this.name = 'IntegrationHostNotAllowedError';
26656
- this.integrationName = integrationName;
26657
- this.disallowedHost = disallowedHost;
26658
- }
26659
- }
26660
- const __kodyGetIntegrationAllowedHosts = (integration) => {
26661
- const hosts = new Set();
26662
- if (integration.requiredHosts) {
26663
- for (const host of integration.requiredHosts) {
26664
- const normalized = host.trim().toLowerCase();
26665
- if (normalized) hosts.add(normalized);
26666
- }
26667
- }
26668
- if (integration.apiBaseUrl) {
26669
- const apiHost = new URL(integration.apiBaseUrl).hostname.trim().toLowerCase();
26670
- if (apiHost) hosts.add(apiHost);
26671
- }
26672
- return Array.from(hosts);
26673
- };
26674
- const __kodyAssertIntegrationHostAllowed = (integrationName, integration, url) => {
26675
- let resolvedUrl;
26676
- if (typeof url === 'string') {
26677
- if (url.startsWith('//')) {
26678
- resolvedUrl = \`https:\${url}\`;
26679
- } else if (url.startsWith('/')) {
26680
- return;
26681
- } else {
26682
- resolvedUrl = url;
26683
- }
26684
- } else if (url instanceof URL) {
26685
- resolvedUrl = url.href;
26686
- } else if (url instanceof Request) {
26687
- resolvedUrl = url.url;
26688
- } else {
26689
- return;
26690
- }
26691
- let requestHost;
26692
- try {
26693
- requestHost = new URL(resolvedUrl).hostname.trim().toLowerCase();
26694
- } catch {
26695
- return;
26696
- }
26697
- if (!requestHost) return;
26698
- const allowedHosts = __kodyGetIntegrationAllowedHosts(integration);
26699
- if (allowedHosts.length === 0) {
26700
- throw new Error(
26701
- \`Integration "\${integrationName}" has no allowed hosts configured (requiredHosts and apiBaseUrl are both empty). \` +
26702
- \`Cannot attach credentials without a host allowlist.\`
26703
- );
26704
- }
26705
- if (!allowedHosts.includes(requestHost)) {
26706
- throw new IntegrationHostNotAllowedError(integrationName, requestHost);
26707
- }
26708
- };
26709
- const __kodyBuildAccessTokenAuthorizationHeader = (providerName, _integration) => {
26710
- const name = String(providerName ?? '').trim();
26711
- if (!name) {
26712
- throw new Error('Integration name is required.');
26713
- }
26714
- return \`Bearer {{integration-token:\${name}}}\`;
26715
- };
26716
- const __kodyCreateBearerRequest = (request, authorization) => {
26717
- const headers = new Headers(request.headers);
26718
- headers.set('Authorization', authorization);
26719
- return new Request(request, { headers });
26720
- };
26721
- const __kodyIsMissingAccessTokenSecretError = (error, providerName) => {
26722
- return (
26723
- error instanceof Error &&
26724
- error.message ===
26725
- \`Integration "\${providerName}" does not have a stored access token.\`
26726
- );
26727
- };
26728
- const __kodyParseSecretNameOrPlaceholder = (value, fieldName) => {
26729
- const trimmed = String(value ?? '').trim();
26730
- if (!trimmed) {
26731
- throw new Error(
26732
- \`\${fieldName} is required.\`,
26733
- );
26734
- }
26735
- if (trimmed.startsWith('{{') && trimmed.endsWith('}}')) {
26736
- const match = /^\\{\\{secret:([a-zA-Z0-9._-]+)(?:\\|scope=(session|package|user))?\\}}$/.exec(trimmed);
26737
- if (!match) {
26738
- throw new Error(
26739
- \`\${fieldName} must be a saved secret name or a single {{secret:\u2026}} opaque ref.\`,
26740
- );
26741
- }
26742
- const scope = match[2];
26743
- return {
26744
- name: match[1],
26745
- scope:
26746
- scope === 'package' || scope === 'session' || scope === 'user'
26747
- ? scope
26748
- : null,
26749
- };
26750
- }
26751
- if (!/^[a-zA-Z0-9._-]+$/.test(trimmed)) {
26752
- throw new Error(
26753
- \`\${fieldName} must be a saved secret name using letters, numbers, dots, underscores, or hyphens, or a single {{secret:\u2026}} opaque ref.\`,
26754
- );
26755
- }
26756
- return { name: trimmed, scope: null };
26757
- };
26758
- const __kodyNormalizeOptionalSecretScope = (scope) => {
26759
- if (scope == null) return null;
26760
- if (scope === 'package' || scope === 'session' || scope === 'user') return scope;
26761
- throw new Error(\`Unsupported secret scope "\${scope}".\`);
26762
- };
26763
- const __kodyResolveBasicAuthSecretScope = (input) => {
26764
- const explicit = __kodyNormalizeOptionalSecretScope(input.explicitScope);
26765
- if (explicit != null) return explicit;
26766
- const usernameScope = input.usernameScope;
26767
- const passwordScope = input.passwordScope;
26768
- if (usernameScope == null) return passwordScope;
26769
- if (passwordScope == null) return usernameScope;
26770
- if (usernameScope !== passwordScope) {
26771
- throw new Error(
26772
- 'usernameSecret and passwordSecret opaque refs disagree on scope. Pass scope explicitly or use matching refs.',
26773
- );
26774
- }
26775
- return usernameScope;
26776
- };
26777
- const __kodyBuildBasicAuthSecretPlaceholder = (input) => {
26778
- const username = __kodyParseSecretNameOrPlaceholder(input.usernameSecret, 'usernameSecret');
26779
- const password = __kodyParseSecretNameOrPlaceholder(input.passwordSecret, 'passwordSecret');
26780
- const scope = __kodyResolveBasicAuthSecretScope({
26781
- explicitScope: input.scope,
26782
- usernameScope: username.scope,
26783
- passwordScope: password.scope,
26784
- });
26785
- return scope
26786
- ? \`{{secret-basic:username=\${username.name},password=\${password.name}|scope=\${scope}}}\`
26787
- : \`{{secret-basic:username=\${username.name},password=\${password.name}}}\`;
26788
- };
26789
- const secretHeaders = {
26790
- basic(input) {
26791
- return __kodyBuildBasicAuthSecretPlaceholder(input);
26792
- },
26793
- };
26794
- const __kodyReadIntegrationConfig = async (providerName) => {
26795
- const result = await ${kodyCallDispatcherName}(${JSON.stringify(INTEGRATION_RUNTIME_CONFIG_TOOL_NAME)}, { name: providerName });
26796
- const integration = result?.integration ?? null;
26797
- if (!integration) {
26798
- throw new Error(\`Integration "\${providerName}" was not found.\`);
26799
- }
26800
- return integration;
26801
- };
26802
- const __kodyGetNormalizedApiBaseUrl = (integration) => {
26803
- if (!integration.apiBaseUrl) return null;
26804
- return integration.apiBaseUrl.endsWith('/')
26805
- ? integration.apiBaseUrl.slice(0, -1)
26806
- : integration.apiBaseUrl;
26807
- };
26808
- const __kodyGetRuntimeOrigin = () => {
26809
- const origin = globalThis.location?.origin ?? null;
26810
- return typeof origin === 'string' && origin.length > 0 ? origin : null;
26811
- };
26812
- const __kodyResolveRelativeUrl = (pathname, integration) => {
26813
- const normalizedBase = __kodyGetNormalizedApiBaseUrl(integration);
26814
- if (!normalizedBase) {
26815
- throw new Error(
26816
- \`Integration "\${integration.name}" does not define apiBaseUrl for relative requests.\`,
26817
- );
26818
- }
26819
- return new URL(\`\${normalizedBase}\${pathname}\`);
26820
- };
26821
- const __kodyGetRelativePathFromRequest = (input, integration) => {
26822
- const requestUrl = new URL(input.url);
26823
- const normalizedBase = __kodyGetNormalizedApiBaseUrl(integration);
26824
- if (normalizedBase && requestUrl.href.startsWith(normalizedBase)) {
26825
- return null;
26826
- }
26827
- const runtimeOrigin = __kodyGetRuntimeOrigin();
26828
- if (!runtimeOrigin || requestUrl.origin !== runtimeOrigin) {
26829
- return null;
26830
- }
26831
- return \`\${requestUrl.pathname}\${requestUrl.search}\${requestUrl.hash}\`;
26832
- };
26833
- const __kodyResolveRequestUrl = (input, integration) => {
26834
- if (typeof input === 'string' && input.startsWith('/')) {
26835
- return __kodyResolveRelativeUrl(input, integration);
26836
- }
26837
- if (input instanceof URL) return input;
26838
- if (typeof input === 'string') return input;
26839
- if (input instanceof Request) {
26840
- const relativePath = __kodyGetRelativePathFromRequest(input, integration);
26841
- if (relativePath) {
26842
- return new Request(__kodyResolveRelativeUrl(relativePath, integration), input);
26843
- }
26844
- }
26845
- return input;
26846
- };
26847
- const __kodyRefreshIntegrationTokensHostSide = async (providerName) => {
26848
- const result = await ${kodyCallDispatcherName}('integrationTokenRefresh', { name: providerName });
26849
- if (result?.ok !== true) {
26850
- throw new Error(
26851
- \`Host-side token refresh for integration "\${providerName}" did not succeed.\`,
26852
- );
26853
- }
26854
- return result.refreshed !== false;
26855
- };
26856
- const __kodyCreateAuthenticatedFetch = async (providerName) => {
26857
- const integration = await __kodyReadIntegrationConfig(providerName);
26858
- // Both lanes refresh host-side and retry with a placeholder header the
26859
- // gateway resolves to the fresh token, so the raw token never enters the
26860
- // sandbox.
26861
- const retryAuthorizationHeader = async () => {
26862
- const refreshed = await __kodyRefreshIntegrationTokensHostSide(providerName);
26863
- return refreshed
26864
- ? __kodyBuildAccessTokenAuthorizationHeader(providerName, integration)
26865
- : null;
26866
- };
26867
- return async (input, init) => {
26868
- const resolvedUrl = __kodyResolveRequestUrl(input, integration);
26869
- __kodyAssertIntegrationHostAllowed(providerName, integration, resolvedUrl);
26870
- const request = new Request(resolvedUrl, init);
26871
- const retryRequest = request.clone();
26872
- let response;
26873
- try {
26874
- response = await fetch(
26875
- __kodyCreateBearerRequest(
26876
- request,
26877
- __kodyBuildAccessTokenAuthorizationHeader(providerName, integration),
26878
- ),
26879
- );
26880
- } catch (error) {
26881
- if (!__kodyIsMissingAccessTokenSecretError(error, providerName)) throw error;
26882
- const retryAuthorization = await retryAuthorizationHeader();
26883
- if (!retryAuthorization) throw error;
26884
- return fetch(__kodyCreateBearerRequest(retryRequest, retryAuthorization));
26885
- }
26886
- if (!(await __kodyResponseIndicatesAuthFailure(response, integration))) {
26887
- return response;
26888
- }
26889
- const retryAuthorization = await retryAuthorizationHeader();
26890
- if (!retryAuthorization) return response;
26891
- await response.body?.cancel();
26892
- return fetch(__kodyCreateBearerRequest(retryRequest, retryAuthorization));
26893
- };
26894
- };
26895
- const __kodySlackAuthErrorCodes = new Set([
26896
- 'token_expired',
26897
- 'token_revoked',
26898
- 'invalid_auth',
26899
- 'not_authed',
26900
- ]);
26901
- const __kodyHostLooksLikeSlack = (value) => {
26902
- const lower = String(value ?? '').toLowerCase();
26903
- return lower.includes('slack.com') || lower.includes('files.slack.com');
26904
- };
26905
- const __kodyIsSlackIntegration = (integration) => {
26906
- if (String(integration?.name ?? '').startsWith('slack')) return true;
26907
- if (__kodyHostLooksLikeSlack(integration?.apiBaseUrl ?? '')) return true;
26908
- return (integration?.requiredHosts ?? []).some((host) =>
26909
- __kodyHostLooksLikeSlack(host),
26910
- );
26911
- };
26912
- const __kodyIsSlackFilesHtmlLoginResponse = (response, contentType) => {
26913
- if (!String(contentType).toLowerCase().includes('text/html')) return false;
26914
- try {
26915
- return new URL(response.url).hostname === 'files.slack.com';
26916
- } catch {
26917
- return false;
26918
- }
26919
- };
26920
- const __kodyResponseIndicatesAuthFailure = async (response, integration) => {
26921
- if (response.status === 401) return true;
26922
- if (!__kodyIsSlackIntegration(integration)) return false;
26923
- const contentType = response.headers.get('content-type') ?? '';
26924
- if (__kodyIsSlackFilesHtmlLoginResponse(response, contentType)) return true;
26925
- if (!contentType.toLowerCase().includes('application/json')) return false;
26926
- try {
26927
- const body = await response.clone().json();
26928
- if (!body || typeof body !== 'object' || Array.isArray(body)) return false;
26929
- return (
26930
- body.ok === false &&
26931
- typeof body.error === 'string' &&
26932
- __kodySlackAuthErrorCodes.has(body.error)
26933
- );
26934
- } catch {
26935
- return false;
26936
- }
26937
- };
26938
- const __kodyOauthClientCredentials = async (input) => {
26939
- const authStyle = input.authStyle ?? 'basic';
26940
- if (authStyle !== 'basic') {
26941
- throw new Error(\`Unsupported OAuth client_credentials authStyle "\${authStyle}".\`);
26942
- }
26943
- const body = new URLSearchParams(input.body ?? {});
26944
- body.set('grant_type', 'client_credentials');
26945
- const headers = new Headers(input.headers);
26946
- if (!headers.has('Accept')) {
26947
- headers.set('Accept', 'application/json');
26948
- }
26949
- headers.set('Content-Type', 'application/x-www-form-urlencoded');
26950
- headers.set(
26951
- 'Authorization',
26952
- secretHeaders.basic({
26953
- usernameSecret: input.clientIdSecret,
26954
- passwordSecret: input.clientSecretSecret,
26955
- scope: input.scope,
26956
- }),
26957
- );
26958
- const response = await fetch(input.tokenUrl, {
26959
- method: 'POST',
26960
- headers,
26961
- body: body.toString(),
26962
- });
26963
- const payload = await response.json();
26964
- if (!response.ok) {
26965
- throw new Error(
26966
- \`OAuth client_credentials request failed with HTTP \${response.status}.\`,
26967
- );
26968
- }
26969
- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
26970
- throw new Error('OAuth client_credentials response was not a JSON object.');
26971
- }
26972
- // The fetch gateway sealed access_token and refresh_token (ADR 0068).
26973
- return payload;
26974
- };
26975
- const createAuthenticatedFetch = async (providerName) =>
26976
- __kodyCreateAuthenticatedFetch(providerName);
26977
- const oauthClientCredentials = async (input) =>
26978
- __kodyOauthClientCredentials(input);
26979
- `.trim();
26980
- }
26981
- var INTEGRATION_RUNTIME_CONFIG_TOOL_NAME;
26982
- var init_kody_runtime_utils = __esm({
26983
- "../worker/src/mcp/execute-modules/kody-runtime-utils.ts"() {
26984
- "use strict";
26985
- init_kody_evaluate_bindings();
26986
- init_placeholders();
26987
- init_integration_host_allowlist();
26988
- INTEGRATION_RUNTIME_CONFIG_TOOL_NAME = "__kodyIntegrationRuntimeConfig";
26989
- }
26990
- });
26991
-
26992
- // ../worker/src/package-runtime/package-bound-runtime-exports.ts
26993
- function packageBoundRuntimeCreatorNames() {
26994
- const lexical = [
26995
- "__kodyCreatePackageBoundFetch",
26996
- "__kodyCreatePackageBoundKody"
26997
- ];
26998
- return [
26999
- ...new Set(
27000
- packageBoundRuntimeExports.map((entry) => entry.creator).filter((creator) => !lexical.includes(creator))
27001
- ),
27002
- ...lexical
27003
- ];
27004
- }
27005
- function createPackageBoundRuntimeExportLines(packageId) {
27006
- const id = JSON.stringify(packageId);
27007
- const lines = [
27008
- `export const __kodyBoundFetch = __kodyCreatePackageBoundFetch(${id});`
27009
- ];
27010
- let credentialRuntimeEmitted = false;
27011
- for (const entry of packageBoundRuntimeExports) {
27012
- if (entry.creator === "__kodyCreatePackageBoundCredentialRuntime") {
27013
- if (!credentialRuntimeEmitted) {
27014
- lines.push(`const ${credentialRuntimeName} = ${entry.creator}(${id});`);
27015
- credentialRuntimeEmitted = true;
27016
- }
27017
- lines.push(
27018
- `export const ${entry.name} = ${credentialRuntimeName}.${entry.name};`
27019
- );
27020
- continue;
27021
- }
27022
- lines.push(`export const ${entry.name} = ${entry.creator}(${id});`);
27023
- }
27024
- return lines.join("\n");
27025
- }
27026
- var packageBoundRuntimeExports, packageBoundRuntimeExportNames, credentialRuntimeName;
27027
- var init_package_bound_runtime_exports = __esm({
27028
- "../worker/src/package-runtime/package-bound-runtime-exports.ts"() {
27029
- "use strict";
27030
- packageBoundRuntimeExports = [
27031
- { name: "kody", creator: "__kodyCreatePackageBoundKody" },
27032
- { name: "packageStorage", creator: "__kodyCreatePackageBoundStorage" },
27033
- { name: "packageSecrets", creator: "__kodyCreatePackageBoundSecrets" },
27034
- {
27035
- name: "createAuthenticatedFetch",
27036
- creator: "__kodyCreatePackageBoundAuthenticatedFetch"
27037
- },
27038
- {
27039
- name: "oauthClientCredentials",
27040
- creator: "__kodyCreatePackageBoundOauthClientCredentials"
27041
- },
27042
- { name: "credential", creator: "__kodyCreatePackageBoundCredentialRuntime" },
27043
- { name: "credentials", creator: "__kodyCreatePackageBoundCredentialRuntime" }
27044
- ];
27045
- packageBoundRuntimeExportNames = packageBoundRuntimeExports.map((entry) => entry.name);
27046
- credentialRuntimeName = "__kodyPackageCredentialRuntime";
27047
- }
27048
- });
27049
-
27050
26423
  // ../worker/src/d1-like-pattern.ts
27051
26424
  var init_d1_like_pattern = __esm({
27052
26425
  "../worker/src/d1-like-pattern.ts"() {
@@ -27618,6 +26991,7 @@ var init_reserved_usernames = __esm({
27618
26991
  "g"
27619
26992
  );
27620
26993
  permanentlyReservedSystemLocals = [
26994
+ "news",
27621
26995
  "kody",
27622
26996
  "support",
27623
26997
  "abuse",
@@ -29141,6 +28515,864 @@ var init_package_import_resolution = __esm({
29141
28515
  }
29142
28516
  });
29143
28517
 
28518
+ // ../worker/src/package-runtime/module-graph-path-basics.ts
28519
+ function joinPath(...parts) {
28520
+ return parts.join("/").replace(/\/+/g, "/").replace(/\/\.\//g, "/");
28521
+ }
28522
+ function dirname(filePath) {
28523
+ const normalized = filePath.replace(/\/+/g, "/");
28524
+ const separator = normalized.lastIndexOf("/");
28525
+ return separator === -1 ? "." : normalized.slice(0, separator) || ".";
28526
+ }
28527
+ function relativePath(fromDir, toPath) {
28528
+ const fromParts = fromDir.split("/").filter(Boolean);
28529
+ const toParts = toPath.split("/").filter(Boolean);
28530
+ let sharedIndex = 0;
28531
+ while (sharedIndex < fromParts.length && sharedIndex < toParts.length && fromParts[sharedIndex] === toParts[sharedIndex]) {
28532
+ sharedIndex += 1;
28533
+ }
28534
+ const upward = fromParts.slice(sharedIndex).map(() => "..");
28535
+ const downward = toParts.slice(sharedIndex);
28536
+ return [...upward, ...downward].join("/");
28537
+ }
28538
+ function createRelativeImportSpecifier(fromPath, targetPath) {
28539
+ const fromDir = dirname(fromPath);
28540
+ const relative = relativePath(fromDir, targetPath);
28541
+ const normalized = relative === "." || relative.startsWith("./") || relative.startsWith("../") ? relative : `./${relative}`;
28542
+ return normalized.replaceAll("\\", "/");
28543
+ }
28544
+ function normalizeWorkspaceModulePath(path) {
28545
+ const parts = [];
28546
+ for (const segment of path.replace(/\\/g, "/").split("/")) {
28547
+ if (!segment || segment === ".") continue;
28548
+ if (segment === "..") {
28549
+ parts.pop();
28550
+ continue;
28551
+ }
28552
+ parts.push(segment);
28553
+ }
28554
+ return parts.join("/");
28555
+ }
28556
+ var runtimeModulePath;
28557
+ var init_module_graph_path_basics = __esm({
28558
+ "../worker/src/package-runtime/module-graph-path-basics.ts"() {
28559
+ "use strict";
28560
+ runtimeModulePath = ".__kody_virtual__/runtime.js";
28561
+ }
28562
+ });
28563
+
28564
+ // ../worker/src/package-runtime/module-graph-paths.ts
28565
+ function resolveRelativeModulePath(fromPath, specifier) {
28566
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) {
28567
+ return null;
28568
+ }
28569
+ return normalizeWorkspaceModulePath(joinPath(dirname(fromPath), specifier));
28570
+ }
28571
+ function encodePathKey(value) {
28572
+ return Array.from(
28573
+ new TextEncoder().encode(value),
28574
+ (byte) => byte.toString(16).padStart(2, "0")
28575
+ ).join("");
28576
+ }
28577
+ function encodePathKeyAsPath(value) {
28578
+ const encoded = encodePathKey(value);
28579
+ const chunks = encoded.match(/.{1,96}/g);
28580
+ return chunks?.join("/") ?? encoded;
28581
+ }
28582
+ function decodePathKey(value) {
28583
+ const bytes = value.match(/[0-9a-f]{2}/gi);
28584
+ if (!bytes || bytes.join("") !== value) return null;
28585
+ try {
28586
+ return new TextDecoder().decode(
28587
+ new Uint8Array(bytes.map((byte) => Number.parseInt(byte, 16)))
28588
+ );
28589
+ } catch {
28590
+ return null;
28591
+ }
28592
+ }
28593
+ function linkedPackageImportPath(specifier) {
28594
+ return `${linkedPackageImportPrefix}/${createPackageProxyPathSegment(specifier)}.js`;
28595
+ }
28596
+ function createPackageProxyPathSegment(specifier) {
28597
+ const parsed = parseKodyPackageSpecifier(specifier);
28598
+ return encodePathKey(
28599
+ `${parsed.packageName}#${normalizePackageExportKey(parsed.exportName)}`
28600
+ );
28601
+ }
28602
+ function createPackageSpecifierFromProxyPath(modulePath) {
28603
+ const normalizedPath = normalizeWorkspaceModulePath(modulePath);
28604
+ const prefix2 = `${dynamicPackageImportProxyPrefix}/`;
28605
+ const prefixIndex = normalizedPath.indexOf(prefix2);
28606
+ if (prefixIndex === -1) return null;
28607
+ const encodedSegment = normalizedPath.slice(prefixIndex + prefix2.length).split("/")[0]?.replace(/\.js$/, "");
28608
+ if (!encodedSegment) return null;
28609
+ const decoded = decodePathKey(encodedSegment);
28610
+ const separator = decoded?.indexOf("#") ?? -1;
28611
+ if (!decoded || separator === -1) return null;
28612
+ const packageName = decoded.slice(0, separator);
28613
+ const exportName = decoded.slice(separator + 1);
28614
+ if (!packageName.startsWith("@")) return null;
28615
+ const exportSuffix = exportName && exportName !== "." ? `/${exportName.replace(/^\.?\//, "")}` : "";
28616
+ return `capabilities:${packageName}${exportSuffix}`;
28617
+ }
28618
+ function unescapeStringLiteralText(text) {
28619
+ return text.replace(
28620
+ /\\(?:u\{([0-9a-f]+)\}|u([0-9a-f]{4})|x([0-9a-f]{2})|\r\n|[\s\S])/gi,
28621
+ (match2, braced, unicode, hex3) => {
28622
+ const code2 = braced ?? unicode ?? hex3;
28623
+ if (code2 != null) {
28624
+ const codePoint = Number.parseInt(code2, 16);
28625
+ return codePoint <= 1114111 ? String.fromCodePoint(codePoint) : "";
28626
+ }
28627
+ const escaped = match2.slice(1);
28628
+ return /^(?:\r\n|[\n\r\u2028\u2029])$/.test(escaped) ? "" : escaped;
28629
+ }
28630
+ );
28631
+ }
28632
+ function percentDecodeText(text) {
28633
+ return text.replace(
28634
+ /%([0-9a-f]{2})/gi,
28635
+ (_match, hex3) => String.fromCharCode(Number.parseInt(hex3, 16))
28636
+ );
28637
+ }
28638
+ function specifierTargetsKodyVirtualModule(specifier) {
28639
+ return kodyVirtualModulePattern.test(specifier) || specifier.includes("%") && kodyVirtualModulePattern.test(percentDecodeText(specifier));
28640
+ }
28641
+ function textMentionsKodyVirtualModule(text) {
28642
+ if (kodyVirtualModulePattern.test(text)) return true;
28643
+ const unescaped = text.includes("\\") ? unescapeStringLiteralText(text) : text;
28644
+ if (unescaped !== text && kodyVirtualModulePattern.test(unescaped)) {
28645
+ return true;
28646
+ }
28647
+ return unescaped.includes("%") && kodyVirtualModulePattern.test(percentDecodeText(unescaped));
28648
+ }
28649
+ function resolveWorkspaceSourceFilePath(input3) {
28650
+ const basePath = normalizeWorkspaceModulePath(input3.path);
28651
+ const candidates = [
28652
+ basePath,
28653
+ `${basePath}.ts`,
28654
+ `${basePath}.tsx`,
28655
+ `${basePath}.js`,
28656
+ `${basePath}.jsx`,
28657
+ `${basePath}.mts`,
28658
+ `${basePath}.cts`,
28659
+ `${basePath}.mjs`,
28660
+ `${basePath}.cjs`,
28661
+ joinPath(basePath, "index.ts"),
28662
+ joinPath(basePath, "index.tsx"),
28663
+ joinPath(basePath, "index.js"),
28664
+ joinPath(basePath, "index.jsx"),
28665
+ joinPath(basePath, "index.mts"),
28666
+ joinPath(basePath, "index.cts"),
28667
+ joinPath(basePath, "index.mjs"),
28668
+ joinPath(basePath, "index.cjs")
28669
+ ];
28670
+ const substitutionBase = basePath.replace(/\.(?:js|jsx|mjs|cjs)$/, "");
28671
+ if (substitutionBase !== basePath) {
28672
+ candidates.push(
28673
+ `${substitutionBase}.ts`,
28674
+ `${substitutionBase}.tsx`,
28675
+ `${substitutionBase}.mts`,
28676
+ `${substitutionBase}.cts`,
28677
+ `${substitutionBase}.mjs`,
28678
+ `${substitutionBase}.cjs`
28679
+ );
28680
+ }
28681
+ return candidates.find((candidate) => input3.files[candidate] != null) ?? null;
28682
+ }
28683
+ var publicRuntimeModulePath, packageRuntimeModulePrefix, packageManifestPath2, wranglerConfigPaths, rootSourcePrefix, packageSourcePrefix, packageImportProxyPrefix, linkedPackageImportPrefix, dynamicPackageImportProxyPrefix, dynamicPackageImportArtifactSegment, dynamicPackageImportSpecifierExportName, dynamicPackageImportResolvedMarker, kodyVirtualModulePattern;
28684
+ var init_module_graph_paths = __esm({
28685
+ "../worker/src/package-runtime/module-graph-paths.ts"() {
28686
+ "use strict";
28687
+ init_manifest();
28688
+ init_package_import_resolution();
28689
+ init_module_graph_path_basics();
28690
+ init_module_graph_path_basics();
28691
+ publicRuntimeModulePath = ".__kody_virtual__/public-runtime.js";
28692
+ packageRuntimeModulePrefix = ".__kody_virtual__/package-runtime";
28693
+ packageManifestPath2 = "package.json";
28694
+ wranglerConfigPaths = [
28695
+ "wrangler.toml",
28696
+ "wrangler.json",
28697
+ "wrangler.jsonc"
28698
+ ];
28699
+ rootSourcePrefix = ".__kody_root__";
28700
+ packageSourcePrefix = ".__kody_packages__";
28701
+ packageImportProxyPrefix = ".__kody_virtual__/imports";
28702
+ linkedPackageImportPrefix = ".__kody_linked__";
28703
+ dynamicPackageImportProxyPrefix = ".__kody_virtual__/dynamic-imports";
28704
+ dynamicPackageImportArtifactSegment = ".__kody_current__";
28705
+ dynamicPackageImportSpecifierExportName = "__kodyDynamicPackageSpecifier";
28706
+ dynamicPackageImportResolvedMarker = "__kodyDynamicPackageResolved";
28707
+ kodyVirtualModulePattern = /__kody_virtual__/i;
28708
+ }
28709
+ });
28710
+
28711
+ // ../worker/src/package-runtime/bundle-artifact-manifest.ts
28712
+ function moduleBytes(module) {
28713
+ if (typeof module === "string") return textEncoder2.encode(module).byteLength;
28714
+ let bytes = 0;
28715
+ for (const source of [module.js, module.cjs, module.text]) {
28716
+ if (typeof source === "string") {
28717
+ bytes += textEncoder2.encode(source).byteLength;
28718
+ }
28719
+ }
28720
+ if (module.data !== void 0) bytes += module.data.byteLength;
28721
+ if (module.json !== void 0) {
28722
+ bytes += textEncoder2.encode(JSON.stringify(module.json) ?? "").byteLength;
28723
+ }
28724
+ return bytes;
28725
+ }
28726
+ function moduleRole(modulePath, mainModule) {
28727
+ if (modulePath === mainModule) return "main";
28728
+ const path = `/${modulePath}`;
28729
+ if (path.includes(`/${linkedArtifactsSegment}`)) return "linked-artifact";
28730
+ if (path.includes(`/${linkedSegment}`)) return "linked-import";
28731
+ return "module";
28732
+ }
28733
+ function createBundleArtifactManifest(input3) {
28734
+ const modules = {};
28735
+ let totalBytes = 0;
28736
+ for (const [modulePath, module] of Object.entries(input3.modules)) {
28737
+ const bytes = moduleBytes(module);
28738
+ totalBytes += bytes;
28739
+ modules[modulePath] = {
28740
+ role: moduleRole(modulePath, input3.mainModule),
28741
+ bytes
28742
+ };
28743
+ }
28744
+ return { version: bundleArtifactManifestVersion, totalBytes, modules };
28745
+ }
28746
+ function parseStoredBundleArtifactManifest(stored, modulePaths) {
28747
+ if (!stored || typeof stored !== "object") return null;
28748
+ const manifest = stored;
28749
+ if (manifest.version !== bundleArtifactManifestVersion) return null;
28750
+ if (!Number.isSafeInteger(manifest.totalBytes)) return null;
28751
+ if (!manifest.modules || typeof manifest.modules !== "object") return null;
28752
+ const entries = Object.entries(manifest.modules);
28753
+ if (entries.length !== modulePaths.length) return null;
28754
+ let moduleBytesSum = 0;
28755
+ for (const modulePath of modulePaths) {
28756
+ const entry = manifest.modules[modulePath];
28757
+ if (!entry || typeof entry !== "object") return null;
28758
+ if (typeof entry.role !== "string" || !moduleRoles.has(entry.role)) {
28759
+ return null;
28760
+ }
28761
+ const bytes = entry.bytes;
28762
+ if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 0) {
28763
+ return null;
28764
+ }
28765
+ moduleBytesSum += bytes;
28766
+ }
28767
+ if (manifest.totalBytes !== moduleBytesSum) return null;
28768
+ return manifest;
28769
+ }
28770
+ var bundleArtifactManifestVersion, textEncoder2, linkedSegment, linkedArtifactsSegment, moduleRoles;
28771
+ var init_bundle_artifact_manifest = __esm({
28772
+ "../worker/src/package-runtime/bundle-artifact-manifest.ts"() {
28773
+ "use strict";
28774
+ init_module_graph_paths();
28775
+ bundleArtifactManifestVersion = 1;
28776
+ textEncoder2 = new TextEncoder();
28777
+ linkedSegment = `${linkedPackageImportPrefix}/`;
28778
+ linkedArtifactsSegment = `${linkedPackageImportPrefix}/artifacts/`;
28779
+ moduleRoles = /* @__PURE__ */ new Set([
28780
+ "main",
28781
+ "linked-artifact",
28782
+ "linked-import",
28783
+ "module"
28784
+ ]);
28785
+ }
28786
+ });
28787
+
28788
+ // ../worker/src/package-runtime/published-source-dependencies.ts
28789
+ function getDeclaredPackageDependencies(sourceFiles) {
28790
+ const packageJson = sourceFiles[packageManifestPath3];
28791
+ if (!packageJson) return [];
28792
+ try {
28793
+ const parsed = JSON.parse(packageJson);
28794
+ return Object.keys(parsed.dependencies ?? {}).sort(
28795
+ (left, right) => left.localeCompare(right)
28796
+ );
28797
+ } catch {
28798
+ return [];
28799
+ }
28800
+ }
28801
+ function getMissingInstalledDependencies(input3) {
28802
+ return input3.dependencies.filter(
28803
+ (dependencyName) => input3.sourceFiles[`node_modules/${dependencyName}/package.json`] == null
28804
+ );
28805
+ }
28806
+ function listMissingPublishedSourceInstalledDependencies(sourceFiles) {
28807
+ const dependencies = getDeclaredPackageDependencies(sourceFiles);
28808
+ if (dependencies.length === 0) return [];
28809
+ return getMissingInstalledDependencies({
28810
+ sourceFiles,
28811
+ dependencies
28812
+ });
28813
+ }
28814
+ function createPublishedRuntimeBundleMissingError(input3) {
28815
+ return new Error(
28816
+ `${input3.bundleLabel} declares npm dependencies (${input3.missingDependencies.map((dependency) => `"${dependency}"`).join(
28817
+ ", "
28818
+ )}) but ${publishedRuntimeBundleMissingMessage}. Republish the package so Kody can install dependencies and persist a fresh runtime bundle artifact.`
28819
+ );
28820
+ }
28821
+ function assertPublishedSourceCanRebuildWithoutInstallingDeps(input3) {
28822
+ const missingDependencies = listMissingPublishedSourceInstalledDependencies(
28823
+ input3.sourceFiles
28824
+ );
28825
+ if (missingDependencies.length === 0) return;
28826
+ throw createPublishedRuntimeBundleMissingError({
28827
+ missingDependencies,
28828
+ bundleLabel: input3.bundleLabel
28829
+ });
28830
+ }
28831
+ var packageManifestPath3, publishedRuntimeBundleMissingMessage, publishedNpmBundleRebuildWindowMs;
28832
+ var init_published_source_dependencies = __esm({
28833
+ "../worker/src/package-runtime/published-source-dependencies.ts"() {
28834
+ "use strict";
28835
+ packageManifestPath3 = "package.json";
28836
+ publishedRuntimeBundleMissingMessage = "no published runtime bundle artifact is available yet";
28837
+ publishedNpmBundleRebuildWindowMs = 2 * 60 * 1e3;
28838
+ }
28839
+ });
28840
+
28841
+ // ../worker/src/package-runtime/rewrite-local-execute-secret-fetch.ts
28842
+ function collectTopLevelFetchCollisionNames(source) {
28843
+ if (!source.trim()) return /* @__PURE__ */ new Set();
28844
+ try {
28845
+ const parsed = parseModuleSource(source);
28846
+ const program = parsed.program;
28847
+ const body = program?.body ?? parsed.body;
28848
+ if (!Array.isArray(body)) return /* @__PURE__ */ new Set();
28849
+ const names = /* @__PURE__ */ new Set();
28850
+ for (const statement of body) {
28851
+ if (!statement || typeof statement !== "object") continue;
28852
+ const node2 = statement;
28853
+ if (node2.type === "ImportDeclaration") {
28854
+ for (const specifier of node2.specifiers ?? []) {
28855
+ const local = getBindingIdentifierName(
28856
+ specifier.local
28857
+ );
28858
+ if (local) names.add(local);
28859
+ }
28860
+ continue;
28861
+ }
28862
+ if (node2.type === "FunctionDeclaration" || node2.type === "ClassDeclaration") {
28863
+ const name = getBindingIdentifierName(node2.id);
28864
+ if (name) names.add(name);
28865
+ continue;
28866
+ }
28867
+ if (node2.type === "VariableDeclaration") {
28868
+ for (const declarator of node2.declarations ?? []) {
28869
+ collectPatternBoundNames(declarator.id, names);
28870
+ }
28871
+ continue;
28872
+ }
28873
+ if (node2.type === "ExportNamedDeclaration" && node2.declaration) {
28874
+ const declaration = node2.declaration;
28875
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
28876
+ const name = getBindingIdentifierName(
28877
+ declaration.id
28878
+ );
28879
+ if (name) names.add(name);
28880
+ continue;
28881
+ }
28882
+ if (declaration.type === "VariableDeclaration") {
28883
+ for (const declarator of declaration.declarations ?? []) {
28884
+ collectPatternBoundNames(declarator.id, names);
28885
+ }
28886
+ }
28887
+ }
28888
+ }
28889
+ return names;
28890
+ } catch {
28891
+ return null;
28892
+ }
28893
+ }
28894
+ function getBindingIdentifierName(node2) {
28895
+ if (!node2 || typeof node2 !== "object") return null;
28896
+ const typed = node2;
28897
+ if (typed.type !== "Identifier" || typeof typed.name !== "string") return null;
28898
+ return typed.name;
28899
+ }
28900
+ function collectPatternBoundNames(node2, names) {
28901
+ if (!node2 || typeof node2 !== "object") return;
28902
+ const typed = node2;
28903
+ switch (typed.type) {
28904
+ case "Identifier": {
28905
+ const name = getBindingIdentifierName(typed);
28906
+ if (name) names.add(name);
28907
+ return;
28908
+ }
28909
+ case "ObjectPattern": {
28910
+ for (const property of typed.properties ?? []) {
28911
+ if (!property || typeof property !== "object") continue;
28912
+ const prop = property;
28913
+ if (prop.type === "RestElement") {
28914
+ collectPatternBoundNames(prop.argument, names);
28915
+ continue;
28916
+ }
28917
+ if (prop.type === "ObjectProperty" || prop.type === "Property") {
28918
+ collectPatternBoundNames(prop.value, names);
28919
+ }
28920
+ }
28921
+ return;
28922
+ }
28923
+ case "ArrayPattern": {
28924
+ for (const element of typed.elements ?? []) {
28925
+ collectPatternBoundNames(element, names);
28926
+ }
28927
+ return;
28928
+ }
28929
+ case "AssignmentPattern": {
28930
+ collectPatternBoundNames(typed.left, names);
28931
+ return;
28932
+ }
28933
+ case "RestElement": {
28934
+ collectPatternBoundNames(typed.argument, names);
28935
+ return;
28936
+ }
28937
+ default:
28938
+ return;
28939
+ }
28940
+ }
28941
+ var init_rewrite_local_execute_secret_fetch = __esm({
28942
+ "../worker/src/package-runtime/rewrite-local-execute-secret-fetch.ts"() {
28943
+ "use strict";
28944
+ init_module_source();
28945
+ init_module_graph_path_basics();
28946
+ }
28947
+ });
28948
+
28949
+ // ../worker/src/kody-evaluate-bindings.ts
28950
+ var kodyCallDispatcherName;
28951
+ var init_kody_evaluate_bindings = __esm({
28952
+ "../worker/src/kody-evaluate-bindings.ts"() {
28953
+ "use strict";
28954
+ kodyCallDispatcherName = "__kodyCallDispatcher";
28955
+ }
28956
+ });
28957
+
28958
+ // ../worker/src/mcp/secrets/placeholders.ts
28959
+ var init_placeholders = __esm({
28960
+ "../worker/src/mcp/secrets/placeholders.ts"() {
28961
+ "use strict";
28962
+ }
28963
+ });
28964
+
28965
+ // ../worker/src/mcp/execute-modules/integration-host-allowlist.ts
28966
+ var init_integration_host_allowlist = __esm({
28967
+ "../worker/src/mcp/execute-modules/integration-host-allowlist.ts"() {
28968
+ "use strict";
28969
+ }
28970
+ });
28971
+
28972
+ // ../worker/src/mcp/execute-modules/kody-runtime-utils.ts
28973
+ function createExecuteHelperPrelude() {
28974
+ return `
28975
+ class IntegrationHostNotAllowedError extends Error {
28976
+ constructor(integrationName, disallowedHost) {
28977
+ super(
28978
+ \`Integration "\${integrationName}" does not allow requests to host "\${disallowedHost}". \` +
28979
+ \`The host must be listed in the integration's requiredHosts or match its apiBaseUrl.\`
28980
+ );
28981
+ this.name = 'IntegrationHostNotAllowedError';
28982
+ this.integrationName = integrationName;
28983
+ this.disallowedHost = disallowedHost;
28984
+ }
28985
+ }
28986
+ const __kodyGetIntegrationAllowedHosts = (integration) => {
28987
+ const hosts = new Set();
28988
+ if (integration.requiredHosts) {
28989
+ for (const host of integration.requiredHosts) {
28990
+ const normalized = host.trim().toLowerCase();
28991
+ if (normalized) hosts.add(normalized);
28992
+ }
28993
+ }
28994
+ if (integration.apiBaseUrl) {
28995
+ const apiHost = new URL(integration.apiBaseUrl).hostname.trim().toLowerCase();
28996
+ if (apiHost) hosts.add(apiHost);
28997
+ }
28998
+ return Array.from(hosts);
28999
+ };
29000
+ const __kodyAssertIntegrationHostAllowed = (integrationName, integration, url) => {
29001
+ let resolvedUrl;
29002
+ if (typeof url === 'string') {
29003
+ if (url.startsWith('//')) {
29004
+ resolvedUrl = \`https:\${url}\`;
29005
+ } else if (url.startsWith('/')) {
29006
+ return;
29007
+ } else {
29008
+ resolvedUrl = url;
29009
+ }
29010
+ } else if (url instanceof URL) {
29011
+ resolvedUrl = url.href;
29012
+ } else if (url instanceof Request) {
29013
+ resolvedUrl = url.url;
29014
+ } else {
29015
+ return;
29016
+ }
29017
+ let requestHost;
29018
+ try {
29019
+ requestHost = new URL(resolvedUrl).hostname.trim().toLowerCase();
29020
+ } catch {
29021
+ return;
29022
+ }
29023
+ if (!requestHost) return;
29024
+ const allowedHosts = __kodyGetIntegrationAllowedHosts(integration);
29025
+ if (allowedHosts.length === 0) {
29026
+ throw new Error(
29027
+ \`Integration "\${integrationName}" has no allowed hosts configured (requiredHosts and apiBaseUrl are both empty). \` +
29028
+ \`Cannot attach credentials without a host allowlist.\`
29029
+ );
29030
+ }
29031
+ if (!allowedHosts.includes(requestHost)) {
29032
+ throw new IntegrationHostNotAllowedError(integrationName, requestHost);
29033
+ }
29034
+ };
29035
+ const __kodyBuildAccessTokenAuthorizationHeader = (providerName, _integration) => {
29036
+ const name = String(providerName ?? '').trim();
29037
+ if (!name) {
29038
+ throw new Error('Integration name is required.');
29039
+ }
29040
+ return \`Bearer {{integration-token:\${name}}}\`;
29041
+ };
29042
+ const __kodyCreateBearerRequest = (request, authorization) => {
29043
+ const headers = new Headers(request.headers);
29044
+ headers.set('Authorization', authorization);
29045
+ return new Request(request, { headers });
29046
+ };
29047
+ const __kodyIsMissingAccessTokenSecretError = (error, providerName) => {
29048
+ return (
29049
+ error instanceof Error &&
29050
+ error.message ===
29051
+ \`Integration "\${providerName}" does not have a stored access token.\`
29052
+ );
29053
+ };
29054
+ const __kodyParseSecretNameOrPlaceholder = (value, fieldName) => {
29055
+ const trimmed = String(value ?? '').trim();
29056
+ if (!trimmed) {
29057
+ throw new Error(
29058
+ \`\${fieldName} is required.\`,
29059
+ );
29060
+ }
29061
+ if (trimmed.startsWith('{{') && trimmed.endsWith('}}')) {
29062
+ const match = /^\\{\\{secret:([a-zA-Z0-9._-]+)(?:\\|scope=(session|package|user))?\\}}$/.exec(trimmed);
29063
+ if (!match) {
29064
+ throw new Error(
29065
+ \`\${fieldName} must be a saved secret name or a single {{secret:\u2026}} opaque ref.\`,
29066
+ );
29067
+ }
29068
+ const scope = match[2];
29069
+ return {
29070
+ name: match[1],
29071
+ scope:
29072
+ scope === 'package' || scope === 'session' || scope === 'user'
29073
+ ? scope
29074
+ : null,
29075
+ };
29076
+ }
29077
+ if (!/^[a-zA-Z0-9._-]+$/.test(trimmed)) {
29078
+ throw new Error(
29079
+ \`\${fieldName} must be a saved secret name using letters, numbers, dots, underscores, or hyphens, or a single {{secret:\u2026}} opaque ref.\`,
29080
+ );
29081
+ }
29082
+ return { name: trimmed, scope: null };
29083
+ };
29084
+ const __kodyNormalizeOptionalSecretScope = (scope) => {
29085
+ if (scope == null) return null;
29086
+ if (scope === 'package' || scope === 'session' || scope === 'user') return scope;
29087
+ throw new Error(\`Unsupported secret scope "\${scope}".\`);
29088
+ };
29089
+ const __kodyResolveBasicAuthSecretScope = (input) => {
29090
+ const explicit = __kodyNormalizeOptionalSecretScope(input.explicitScope);
29091
+ if (explicit != null) return explicit;
29092
+ const usernameScope = input.usernameScope;
29093
+ const passwordScope = input.passwordScope;
29094
+ if (usernameScope == null) return passwordScope;
29095
+ if (passwordScope == null) return usernameScope;
29096
+ if (usernameScope !== passwordScope) {
29097
+ throw new Error(
29098
+ 'usernameSecret and passwordSecret opaque refs disagree on scope. Pass scope explicitly or use matching refs.',
29099
+ );
29100
+ }
29101
+ return usernameScope;
29102
+ };
29103
+ const __kodyBuildBasicAuthSecretPlaceholder = (input) => {
29104
+ const username = __kodyParseSecretNameOrPlaceholder(input.usernameSecret, 'usernameSecret');
29105
+ const password = __kodyParseSecretNameOrPlaceholder(input.passwordSecret, 'passwordSecret');
29106
+ const scope = __kodyResolveBasicAuthSecretScope({
29107
+ explicitScope: input.scope,
29108
+ usernameScope: username.scope,
29109
+ passwordScope: password.scope,
29110
+ });
29111
+ return scope
29112
+ ? \`{{secret-basic:username=\${username.name},password=\${password.name}|scope=\${scope}}}\`
29113
+ : \`{{secret-basic:username=\${username.name},password=\${password.name}}}\`;
29114
+ };
29115
+ const secretHeaders = {
29116
+ basic(input) {
29117
+ return __kodyBuildBasicAuthSecretPlaceholder(input);
29118
+ },
29119
+ };
29120
+ const __kodyReadIntegrationConfig = async (providerName) => {
29121
+ const result = await ${kodyCallDispatcherName}(${JSON.stringify(INTEGRATION_RUNTIME_CONFIG_TOOL_NAME)}, { name: providerName });
29122
+ const integration = result?.integration ?? null;
29123
+ if (!integration) {
29124
+ throw new Error(\`Integration "\${providerName}" was not found.\`);
29125
+ }
29126
+ return integration;
29127
+ };
29128
+ const __kodyGetNormalizedApiBaseUrl = (integration) => {
29129
+ if (!integration.apiBaseUrl) return null;
29130
+ return integration.apiBaseUrl.endsWith('/')
29131
+ ? integration.apiBaseUrl.slice(0, -1)
29132
+ : integration.apiBaseUrl;
29133
+ };
29134
+ const __kodyGetRuntimeOrigin = () => {
29135
+ const origin = globalThis.location?.origin ?? null;
29136
+ return typeof origin === 'string' && origin.length > 0 ? origin : null;
29137
+ };
29138
+ const __kodyResolveRelativeUrl = (pathname, integration) => {
29139
+ const normalizedBase = __kodyGetNormalizedApiBaseUrl(integration);
29140
+ if (!normalizedBase) {
29141
+ throw new Error(
29142
+ \`Integration "\${integration.name}" does not define apiBaseUrl for relative requests.\`,
29143
+ );
29144
+ }
29145
+ return new URL(\`\${normalizedBase}\${pathname}\`);
29146
+ };
29147
+ const __kodyGetRelativePathFromRequest = (input, integration) => {
29148
+ const requestUrl = new URL(input.url);
29149
+ const normalizedBase = __kodyGetNormalizedApiBaseUrl(integration);
29150
+ if (normalizedBase && requestUrl.href.startsWith(normalizedBase)) {
29151
+ return null;
29152
+ }
29153
+ const runtimeOrigin = __kodyGetRuntimeOrigin();
29154
+ if (!runtimeOrigin || requestUrl.origin !== runtimeOrigin) {
29155
+ return null;
29156
+ }
29157
+ return \`\${requestUrl.pathname}\${requestUrl.search}\${requestUrl.hash}\`;
29158
+ };
29159
+ const __kodyResolveRequestUrl = (input, integration) => {
29160
+ if (typeof input === 'string' && input.startsWith('/')) {
29161
+ return __kodyResolveRelativeUrl(input, integration);
29162
+ }
29163
+ if (input instanceof URL) return input;
29164
+ if (typeof input === 'string') return input;
29165
+ if (input instanceof Request) {
29166
+ const relativePath = __kodyGetRelativePathFromRequest(input, integration);
29167
+ if (relativePath) {
29168
+ return new Request(__kodyResolveRelativeUrl(relativePath, integration), input);
29169
+ }
29170
+ }
29171
+ return input;
29172
+ };
29173
+ const __kodyRefreshIntegrationTokensHostSide = async (providerName) => {
29174
+ const result = await ${kodyCallDispatcherName}('integrationTokenRefresh', { name: providerName });
29175
+ if (result?.ok !== true) {
29176
+ throw new Error(
29177
+ \`Host-side token refresh for integration "\${providerName}" did not succeed.\`,
29178
+ );
29179
+ }
29180
+ return result.refreshed !== false;
29181
+ };
29182
+ const __kodyCreateAuthenticatedFetch = async (providerName) => {
29183
+ const integration = await __kodyReadIntegrationConfig(providerName);
29184
+ // Both lanes refresh host-side and retry with a placeholder header the
29185
+ // gateway resolves to the fresh token, so the raw token never enters the
29186
+ // sandbox.
29187
+ const retryAuthorizationHeader = async () => {
29188
+ const refreshed = await __kodyRefreshIntegrationTokensHostSide(providerName);
29189
+ return refreshed
29190
+ ? __kodyBuildAccessTokenAuthorizationHeader(providerName, integration)
29191
+ : null;
29192
+ };
29193
+ return async (input, init) => {
29194
+ const resolvedUrl = __kodyResolveRequestUrl(input, integration);
29195
+ __kodyAssertIntegrationHostAllowed(providerName, integration, resolvedUrl);
29196
+ const request = new Request(resolvedUrl, init);
29197
+ const retryRequest = request.clone();
29198
+ let response;
29199
+ try {
29200
+ response = await fetch(
29201
+ __kodyCreateBearerRequest(
29202
+ request,
29203
+ __kodyBuildAccessTokenAuthorizationHeader(providerName, integration),
29204
+ ),
29205
+ );
29206
+ } catch (error) {
29207
+ if (!__kodyIsMissingAccessTokenSecretError(error, providerName)) throw error;
29208
+ const retryAuthorization = await retryAuthorizationHeader();
29209
+ if (!retryAuthorization) throw error;
29210
+ return fetch(__kodyCreateBearerRequest(retryRequest, retryAuthorization));
29211
+ }
29212
+ if (!(await __kodyResponseIndicatesAuthFailure(response, integration))) {
29213
+ return response;
29214
+ }
29215
+ const retryAuthorization = await retryAuthorizationHeader();
29216
+ if (!retryAuthorization) return response;
29217
+ await response.body?.cancel();
29218
+ return fetch(__kodyCreateBearerRequest(retryRequest, retryAuthorization));
29219
+ };
29220
+ };
29221
+ const __kodySlackAuthErrorCodes = new Set([
29222
+ 'token_expired',
29223
+ 'token_revoked',
29224
+ 'invalid_auth',
29225
+ 'not_authed',
29226
+ ]);
29227
+ const __kodyHostLooksLikeSlack = (value) => {
29228
+ const lower = String(value ?? '').toLowerCase();
29229
+ return lower.includes('slack.com') || lower.includes('files.slack.com');
29230
+ };
29231
+ const __kodyIsSlackIntegration = (integration) => {
29232
+ if (String(integration?.name ?? '').startsWith('slack')) return true;
29233
+ if (__kodyHostLooksLikeSlack(integration?.apiBaseUrl ?? '')) return true;
29234
+ return (integration?.requiredHosts ?? []).some((host) =>
29235
+ __kodyHostLooksLikeSlack(host),
29236
+ );
29237
+ };
29238
+ const __kodyIsSlackFilesHtmlLoginResponse = (response, contentType) => {
29239
+ if (!String(contentType).toLowerCase().includes('text/html')) return false;
29240
+ try {
29241
+ return new URL(response.url).hostname === 'files.slack.com';
29242
+ } catch {
29243
+ return false;
29244
+ }
29245
+ };
29246
+ const __kodyResponseIndicatesAuthFailure = async (response, integration) => {
29247
+ if (response.status === 401) return true;
29248
+ if (!__kodyIsSlackIntegration(integration)) return false;
29249
+ const contentType = response.headers.get('content-type') ?? '';
29250
+ if (__kodyIsSlackFilesHtmlLoginResponse(response, contentType)) return true;
29251
+ if (!contentType.toLowerCase().includes('application/json')) return false;
29252
+ try {
29253
+ const body = await response.clone().json();
29254
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return false;
29255
+ return (
29256
+ body.ok === false &&
29257
+ typeof body.error === 'string' &&
29258
+ __kodySlackAuthErrorCodes.has(body.error)
29259
+ );
29260
+ } catch {
29261
+ return false;
29262
+ }
29263
+ };
29264
+ const __kodyOauthClientCredentials = async (input) => {
29265
+ const authStyle = input.authStyle ?? 'basic';
29266
+ if (authStyle !== 'basic') {
29267
+ throw new Error(\`Unsupported OAuth client_credentials authStyle "\${authStyle}".\`);
29268
+ }
29269
+ const body = new URLSearchParams(input.body ?? {});
29270
+ body.set('grant_type', 'client_credentials');
29271
+ const headers = new Headers(input.headers);
29272
+ if (!headers.has('Accept')) {
29273
+ headers.set('Accept', 'application/json');
29274
+ }
29275
+ headers.set('Content-Type', 'application/x-www-form-urlencoded');
29276
+ headers.set(
29277
+ 'Authorization',
29278
+ secretHeaders.basic({
29279
+ usernameSecret: input.clientIdSecret,
29280
+ passwordSecret: input.clientSecretSecret,
29281
+ scope: input.scope,
29282
+ }),
29283
+ );
29284
+ const response = await fetch(input.tokenUrl, {
29285
+ method: 'POST',
29286
+ headers,
29287
+ body: body.toString(),
29288
+ });
29289
+ const payload = await response.json();
29290
+ if (!response.ok) {
29291
+ throw new Error(
29292
+ \`OAuth client_credentials request failed with HTTP \${response.status}.\`,
29293
+ );
29294
+ }
29295
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
29296
+ throw new Error('OAuth client_credentials response was not a JSON object.');
29297
+ }
29298
+ // The fetch gateway sealed access_token and refresh_token (ADR 0068).
29299
+ return payload;
29300
+ };
29301
+ const createAuthenticatedFetch = async (providerName) =>
29302
+ __kodyCreateAuthenticatedFetch(providerName);
29303
+ const oauthClientCredentials = async (input) =>
29304
+ __kodyOauthClientCredentials(input);
29305
+ `.trim();
29306
+ }
29307
+ var INTEGRATION_RUNTIME_CONFIG_TOOL_NAME;
29308
+ var init_kody_runtime_utils = __esm({
29309
+ "../worker/src/mcp/execute-modules/kody-runtime-utils.ts"() {
29310
+ "use strict";
29311
+ init_kody_evaluate_bindings();
29312
+ init_placeholders();
29313
+ init_integration_host_allowlist();
29314
+ INTEGRATION_RUNTIME_CONFIG_TOOL_NAME = "__kodyIntegrationRuntimeConfig";
29315
+ }
29316
+ });
29317
+
29318
+ // ../worker/src/package-runtime/package-bound-runtime-exports.ts
29319
+ function packageBoundRuntimeCreatorNames() {
29320
+ const lexical = [
29321
+ "__kodyCreatePackageBoundFetch",
29322
+ "__kodyCreatePackageBoundKody"
29323
+ ];
29324
+ return [
29325
+ ...new Set(
29326
+ packageBoundRuntimeExports.map((entry) => entry.creator).filter((creator) => !lexical.includes(creator))
29327
+ ),
29328
+ ...lexical
29329
+ ];
29330
+ }
29331
+ function createPackageBoundRuntimeExportLines(packageId) {
29332
+ const id = JSON.stringify(packageId);
29333
+ const lines = [
29334
+ `export const __kodyBoundFetch = __kodyCreatePackageBoundFetch(${id});`
29335
+ ];
29336
+ let credentialRuntimeEmitted = false;
29337
+ for (const entry of packageBoundRuntimeExports) {
29338
+ if (entry.creator === "__kodyCreatePackageBoundCredentialRuntime") {
29339
+ if (!credentialRuntimeEmitted) {
29340
+ lines.push(`const ${credentialRuntimeName} = ${entry.creator}(${id});`);
29341
+ credentialRuntimeEmitted = true;
29342
+ }
29343
+ lines.push(
29344
+ `export const ${entry.name} = ${credentialRuntimeName}.${entry.name};`
29345
+ );
29346
+ continue;
29347
+ }
29348
+ lines.push(`export const ${entry.name} = ${entry.creator}(${id});`);
29349
+ }
29350
+ return lines.join("\n");
29351
+ }
29352
+ var packageBoundRuntimeExports, packageBoundRuntimeExportNames, credentialRuntimeName;
29353
+ var init_package_bound_runtime_exports = __esm({
29354
+ "../worker/src/package-runtime/package-bound-runtime-exports.ts"() {
29355
+ "use strict";
29356
+ packageBoundRuntimeExports = [
29357
+ { name: "kody", creator: "__kodyCreatePackageBoundKody" },
29358
+ { name: "packageStorage", creator: "__kodyCreatePackageBoundStorage" },
29359
+ { name: "packageSecrets", creator: "__kodyCreatePackageBoundSecrets" },
29360
+ {
29361
+ name: "createAuthenticatedFetch",
29362
+ creator: "__kodyCreatePackageBoundAuthenticatedFetch"
29363
+ },
29364
+ {
29365
+ name: "oauthClientCredentials",
29366
+ creator: "__kodyCreatePackageBoundOauthClientCredentials"
29367
+ },
29368
+ { name: "credential", creator: "__kodyCreatePackageBoundCredentialRuntime" },
29369
+ { name: "credentials", creator: "__kodyCreatePackageBoundCredentialRuntime" }
29370
+ ];
29371
+ packageBoundRuntimeExportNames = packageBoundRuntimeExports.map((entry) => entry.name);
29372
+ credentialRuntimeName = "__kodyPackageCredentialRuntime";
29373
+ }
29374
+ });
29375
+
29144
29376
  // ../worker/src/package-runtime/import-specifiers.ts
29145
29377
  function readLiteralStringNode(node2) {
29146
29378
  if (node2 == null || typeof node2 !== "object") return null;
@@ -29380,153 +29612,6 @@ var init_import_specifiers = __esm({
29380
29612
  }
29381
29613
  });
29382
29614
 
29383
- // ../worker/src/package-runtime/module-graph-paths.ts
29384
- function resolveRelativeModulePath(fromPath, specifier) {
29385
- if (!specifier.startsWith("./") && !specifier.startsWith("../")) {
29386
- return null;
29387
- }
29388
- return normalizeWorkspaceModulePath(joinPath(dirname(fromPath), specifier));
29389
- }
29390
- function encodePathKey(value) {
29391
- return Array.from(
29392
- new TextEncoder().encode(value),
29393
- (byte) => byte.toString(16).padStart(2, "0")
29394
- ).join("");
29395
- }
29396
- function encodePathKeyAsPath(value) {
29397
- const encoded = encodePathKey(value);
29398
- const chunks = encoded.match(/.{1,96}/g);
29399
- return chunks?.join("/") ?? encoded;
29400
- }
29401
- function decodePathKey(value) {
29402
- const bytes = value.match(/[0-9a-f]{2}/gi);
29403
- if (!bytes || bytes.join("") !== value) return null;
29404
- try {
29405
- return new TextDecoder().decode(
29406
- new Uint8Array(bytes.map((byte) => Number.parseInt(byte, 16)))
29407
- );
29408
- } catch {
29409
- return null;
29410
- }
29411
- }
29412
- function linkedPackageImportPath(specifier) {
29413
- return `${linkedPackageImportPrefix}/${createPackageProxyPathSegment(specifier)}.js`;
29414
- }
29415
- function createPackageProxyPathSegment(specifier) {
29416
- const parsed = parseKodyPackageSpecifier(specifier);
29417
- return encodePathKey(
29418
- `${parsed.packageName}#${normalizePackageExportKey(parsed.exportName)}`
29419
- );
29420
- }
29421
- function createPackageSpecifierFromProxyPath(modulePath) {
29422
- const normalizedPath = normalizeWorkspaceModulePath(modulePath);
29423
- const prefix2 = `${dynamicPackageImportProxyPrefix}/`;
29424
- const prefixIndex = normalizedPath.indexOf(prefix2);
29425
- if (prefixIndex === -1) return null;
29426
- const encodedSegment = normalizedPath.slice(prefixIndex + prefix2.length).split("/")[0]?.replace(/\.js$/, "");
29427
- if (!encodedSegment) return null;
29428
- const decoded = decodePathKey(encodedSegment);
29429
- const separator = decoded?.indexOf("#") ?? -1;
29430
- if (!decoded || separator === -1) return null;
29431
- const packageName = decoded.slice(0, separator);
29432
- const exportName = decoded.slice(separator + 1);
29433
- if (!packageName.startsWith("@")) return null;
29434
- const exportSuffix = exportName && exportName !== "." ? `/${exportName.replace(/^\.?\//, "")}` : "";
29435
- return `capabilities:${packageName}${exportSuffix}`;
29436
- }
29437
- function unescapeStringLiteralText(text) {
29438
- return text.replace(
29439
- /\\(?:u\{([0-9a-f]+)\}|u([0-9a-f]{4})|x([0-9a-f]{2})|\r\n|[\s\S])/gi,
29440
- (match2, braced, unicode, hex3) => {
29441
- const code2 = braced ?? unicode ?? hex3;
29442
- if (code2 != null) {
29443
- const codePoint = Number.parseInt(code2, 16);
29444
- return codePoint <= 1114111 ? String.fromCodePoint(codePoint) : "";
29445
- }
29446
- const escaped = match2.slice(1);
29447
- return /^(?:\r\n|[\n\r\u2028\u2029])$/.test(escaped) ? "" : escaped;
29448
- }
29449
- );
29450
- }
29451
- function percentDecodeText(text) {
29452
- return text.replace(
29453
- /%([0-9a-f]{2})/gi,
29454
- (_match, hex3) => String.fromCharCode(Number.parseInt(hex3, 16))
29455
- );
29456
- }
29457
- function specifierTargetsKodyVirtualModule(specifier) {
29458
- return kodyVirtualModulePattern.test(specifier) || specifier.includes("%") && kodyVirtualModulePattern.test(percentDecodeText(specifier));
29459
- }
29460
- function textMentionsKodyVirtualModule(text) {
29461
- if (kodyVirtualModulePattern.test(text)) return true;
29462
- const unescaped = text.includes("\\") ? unescapeStringLiteralText(text) : text;
29463
- if (unescaped !== text && kodyVirtualModulePattern.test(unescaped)) {
29464
- return true;
29465
- }
29466
- return unescaped.includes("%") && kodyVirtualModulePattern.test(percentDecodeText(unescaped));
29467
- }
29468
- function resolveWorkspaceSourceFilePath(input3) {
29469
- const basePath = normalizeWorkspaceModulePath(input3.path);
29470
- const candidates = [
29471
- basePath,
29472
- `${basePath}.ts`,
29473
- `${basePath}.tsx`,
29474
- `${basePath}.js`,
29475
- `${basePath}.jsx`,
29476
- `${basePath}.mts`,
29477
- `${basePath}.cts`,
29478
- `${basePath}.mjs`,
29479
- `${basePath}.cjs`,
29480
- joinPath(basePath, "index.ts"),
29481
- joinPath(basePath, "index.tsx"),
29482
- joinPath(basePath, "index.js"),
29483
- joinPath(basePath, "index.jsx"),
29484
- joinPath(basePath, "index.mts"),
29485
- joinPath(basePath, "index.cts"),
29486
- joinPath(basePath, "index.mjs"),
29487
- joinPath(basePath, "index.cjs")
29488
- ];
29489
- const substitutionBase = basePath.replace(/\.(?:js|jsx|mjs|cjs)$/, "");
29490
- if (substitutionBase !== basePath) {
29491
- candidates.push(
29492
- `${substitutionBase}.ts`,
29493
- `${substitutionBase}.tsx`,
29494
- `${substitutionBase}.mts`,
29495
- `${substitutionBase}.cts`,
29496
- `${substitutionBase}.mjs`,
29497
- `${substitutionBase}.cjs`
29498
- );
29499
- }
29500
- return candidates.find((candidate) => input3.files[candidate] != null) ?? null;
29501
- }
29502
- var publicRuntimeModulePath, packageRuntimeModulePrefix, packageManifestPath3, wranglerConfigPaths, rootSourcePrefix, packageSourcePrefix, packageImportProxyPrefix, linkedPackageImportPrefix, dynamicPackageImportProxyPrefix, dynamicPackageImportArtifactSegment, dynamicPackageImportSpecifierExportName, dynamicPackageImportResolvedMarker, kodyVirtualModulePattern;
29503
- var init_module_graph_paths = __esm({
29504
- "../worker/src/package-runtime/module-graph-paths.ts"() {
29505
- "use strict";
29506
- init_manifest();
29507
- init_package_import_resolution();
29508
- init_module_graph_path_basics();
29509
- init_module_graph_path_basics();
29510
- publicRuntimeModulePath = ".__kody_virtual__/public-runtime.js";
29511
- packageRuntimeModulePrefix = ".__kody_virtual__/package-runtime";
29512
- packageManifestPath3 = "package.json";
29513
- wranglerConfigPaths = [
29514
- "wrangler.toml",
29515
- "wrangler.json",
29516
- "wrangler.jsonc"
29517
- ];
29518
- rootSourcePrefix = ".__kody_root__";
29519
- packageSourcePrefix = ".__kody_packages__";
29520
- packageImportProxyPrefix = ".__kody_virtual__/imports";
29521
- linkedPackageImportPrefix = ".__kody_linked__";
29522
- dynamicPackageImportProxyPrefix = ".__kody_virtual__/dynamic-imports";
29523
- dynamicPackageImportArtifactSegment = ".__kody_current__";
29524
- dynamicPackageImportSpecifierExportName = "__kodyDynamicPackageSpecifier";
29525
- dynamicPackageImportResolvedMarker = "__kodyDynamicPackageResolved";
29526
- kodyVirtualModulePattern = /__kody_virtual__/i;
29527
- }
29528
- });
29529
-
29530
29615
  // ../worker/src/package-runtime/runtime-source-modules.ts
29531
29616
  function createRuntimeModuleSource() {
29532
29617
  if (cachedRuntimeModuleSource) {
@@ -31658,7 +31743,8 @@ async function writePublishedBundleArtifact(input3) {
31658
31743
  });
31659
31744
  const serialized = JSON.stringify({
31660
31745
  ...input3.artifact,
31661
- modules: serializeWorkerLoaderModules(input3.artifact.modules)
31746
+ modules: serializeWorkerLoaderModules(input3.artifact.modules),
31747
+ manifest: createBundleArtifactManifest(input3.artifact)
31662
31748
  });
31663
31749
  const kv = getBundleArtifactsKv(input3.env);
31664
31750
  await Promise.all([
@@ -31733,10 +31819,17 @@ function parseStoredPublishedBundleArtifact(stored) {
31733
31819
  createdAt: artifact.createdAt,
31734
31820
  ...artifact.packageBindingRewrite === void 0 ? {} : { packageBindingRewrite: artifact.packageBindingRewrite }
31735
31821
  };
31736
- if (!isRepairableArtifactKind(loaded.kind)) return loaded;
31737
- return repairInlinedFacadeBindingsInArtifact(
31822
+ const manifest = parseStoredBundleArtifactManifest(
31823
+ stored.manifest,
31824
+ Object.keys(loaded.modules)
31825
+ );
31826
+ if (!isRepairableArtifactKind(loaded.kind)) {
31827
+ return manifest ? { ...loaded, manifest } : loaded;
31828
+ }
31829
+ const repaired = repairInlinedFacadeBindingsInArtifact(
31738
31830
  repairPreBindingPublishedArtifact(loaded)
31739
31831
  );
31832
+ return manifest && repaired.modules === loaded.modules ? { ...repaired, manifest } : repaired;
31740
31833
  }
31741
31834
  var sourceSnapshotVersion, sourceManifestSnapshotVersion, bundleArtifactVersion, sourceSnapshotPrefix, sourceManifestSnapshotPrefix, bundleArtifactPrefix, packageAppTemplateVersion, packageAppTemplatePrefix, packageAppClientPointerPrefix;
31742
31835
  var init_published_runtime_artifacts = __esm({
@@ -31744,6 +31837,7 @@ var init_published_runtime_artifacts = __esm({
31744
31837
  "use strict";
31745
31838
  init_base64();
31746
31839
  init_published_source_files();
31840
+ init_bundle_artifact_manifest();
31747
31841
  init_inlined_facade_binding_repair();
31748
31842
  init_pre_binding_artifact_repair();
31749
31843
  sourceSnapshotVersion = 1;
@@ -31779,7 +31873,8 @@ function toDbRowInput(input3) {
31779
31873
  artifactName: input3.artifactName,
31780
31874
  entryPoint: input3.entryPoint,
31781
31875
  kvKey: input3.kvKey,
31782
- dependenciesJson: JSON.stringify(input3.dependencies)
31876
+ dependenciesJson: JSON.stringify(input3.dependencies),
31877
+ totalBytes: input3.totalBytes
31783
31878
  };
31784
31879
  }
31785
31880
  function matchesPublishedBundleArtifactIdentity(input3) {
@@ -31833,7 +31928,8 @@ function preparePublishedBundleArtifactPersist(input3) {
31833
31928
  artifactName,
31834
31929
  entryPoint,
31835
31930
  kvKey,
31836
- dependencies: input3.dependencies
31931
+ dependencies: input3.dependencies,
31932
+ totalBytes: createBundleArtifactManifest(artifact).totalBytes
31837
31933
  })
31838
31934
  };
31839
31935
  }
@@ -31967,6 +32063,7 @@ var init_published_bundle_artifact_persist = __esm({
31967
32063
  "use strict";
31968
32064
  init_published_bundle_artifacts_repo();
31969
32065
  init_package_artifact_targets();
32066
+ init_bundle_artifact_manifest();
31970
32067
  init_pre_binding_artifact_repair();
31971
32068
  init_published_runtime_artifacts();
31972
32069
  }
@@ -33321,7 +33418,7 @@ function createEphemeralGitWorkspace() {
33321
33418
  const store = /* @__PURE__ */ new Map();
33322
33419
  const symlinkTargets = /* @__PURE__ */ new Map();
33323
33420
  const textDecoder2 = new TextDecoder();
33324
- const textEncoder3 = new TextEncoder();
33421
+ const textEncoder4 = new TextEncoder();
33325
33422
  function resolveSymlinkPath(path, target) {
33326
33423
  const parts = target.startsWith("/") ? [] : path.split("/").slice(0, -1).filter(Boolean);
33327
33424
  for (const part of target.split("/")) {
@@ -33364,7 +33461,7 @@ function createEphemeralGitWorkspace() {
33364
33461
  if (target != null && !followSymlink) {
33365
33462
  return {
33366
33463
  type: "symlink",
33367
- size: textEncoder3.encode(target).byteLength,
33464
+ size: textEncoder4.encode(target).byteLength,
33368
33465
  mtime: /* @__PURE__ */ new Date()
33369
33466
  };
33370
33467
  }
@@ -33391,7 +33488,7 @@ function createEphemeralGitWorkspace() {
33391
33488
  writeFile: async (path, data) => {
33392
33489
  const normalized = normalizeFsPath(path);
33393
33490
  symlinkTargets.delete(normalized);
33394
- store.set(normalized, textEncoder3.encode(data));
33491
+ store.set(normalized, textEncoder4.encode(data));
33395
33492
  },
33396
33493
  writeFileBytes: async (path, data) => {
33397
33494
  const normalized = normalizeFsPath(path);
@@ -33454,7 +33551,7 @@ function createEphemeralGitWorkspace() {
33454
33551
  },
33455
33552
  symlink: async (target, path) => {
33456
33553
  const normalized = normalizeFsPath(path);
33457
- store.set(normalized, textEncoder3.encode(target));
33554
+ store.set(normalized, textEncoder4.encode(target));
33458
33555
  symlinkTargets.set(normalized, target);
33459
33556
  }
33460
33557
  };
@@ -184601,7 +184698,7 @@ function resolvePackageExportSourcePath(input3) {
184601
184698
  }) ?? exportPath;
184602
184699
  }
184603
184700
  function readRootPackage(sourceFiles) {
184604
- const packageJson = sourceFiles[packageManifestPath3];
184701
+ const packageJson = sourceFiles[packageManifestPath2];
184605
184702
  if (!packageJson) return null;
184606
184703
  try {
184607
184704
  return {
@@ -184616,7 +184713,7 @@ function readRootPackage(sourceFiles) {
184616
184713
  }
184617
184714
  }
184618
184715
  function isBundlerRootConfigPath(path) {
184619
- return path === packageManifestPath3 || wranglerConfigPaths.includes(path);
184716
+ return path === packageManifestPath2 || wranglerConfigPaths.includes(path);
184620
184717
  }
184621
184718
  function isBundlerRootDependencyPath(path) {
184622
184719
  return path === "node_modules" || path.startsWith("node_modules/");
@@ -185344,6 +185441,7 @@ var publishedPackageArtifactRebuildConcurrency;
185344
185441
  var init_published_bundle_artifacts = __esm({
185345
185442
  "../worker/src/package-runtime/published-bundle-artifacts.ts"() {
185346
185443
  "use strict";
185444
+ init_bundle_artifact_manifest();
185347
185445
  init_pre_binding_artifact_repair();
185348
185446
  init_published_runtime_artifacts();
185349
185447
  init_published_bundle_artifacts_repo();
@@ -185656,6 +185754,7 @@ async function maybeEnsurePublishedArtifactTarget(input3) {
185656
185754
  })
185657
185755
  )) {
185658
185756
  input3.state.files[modulePath] = module;
185757
+ input3.state.moduleRoles.set(modulePath, "published-artifact");
185659
185758
  }
185660
185759
  for (const dependency of artifact.artifact.dependencies) {
185661
185760
  input3.state.publishedArtifactDependencies.push(dependency);
@@ -185762,6 +185861,7 @@ async function materializePackageSourceIntoFiles(state2, loaded) {
185762
185861
  const normalizedPath = normalizePackageWorkspacePath(filePath);
185763
185862
  assertNoKodyVirtualModuleReference(normalizedPath, content);
185764
185863
  const targetPath = joinPath(loaded.prefix, normalizedPath);
185864
+ state2.moduleRoles.set(targetPath, "package-source");
185765
185865
  if (isTypeDeclarationFilePath(normalizedPath)) {
185766
185866
  state2.files[targetPath] = content;
185767
185867
  continue;
@@ -185824,6 +185924,7 @@ async function ensurePackageProxy(state2, specifier) {
185824
185924
  proxyPath,
185825
185925
  absoluteExportPath
185826
185926
  );
185927
+ state2.moduleRoles.set(proxyPath, "import-proxy");
185827
185928
  state2.files[proxyPath] = calleePackageId ? createMeteredPackageImportProxySource({
185828
185929
  targetPath: proxyTarget,
185829
185930
  runtimeSpecifier: createRelativeImportSpecifier(
@@ -185883,10 +185984,12 @@ function createUniqueHelperName(source, baseName) {
185883
185984
  function ensurePackageRuntimeModule(state2, packageId) {
185884
185985
  const modulePath = buildPackageRuntimeModulePath(packageId);
185885
185986
  state2.files[modulePath] ??= createPackageRuntimeModuleSource(packageId);
185987
+ state2.moduleRoles.set(modulePath, "package-runtime");
185886
185988
  return modulePath;
185887
185989
  }
185888
185990
  function ensurePublicRuntimeModule(state2) {
185889
185991
  state2.files[publicRuntimeModulePath] ??= createPublicRuntimeModuleSource();
185992
+ state2.moduleRoles.set(publicRuntimeModulePath, "public-runtime");
185890
185993
  return publicRuntimeModulePath;
185891
185994
  }
185892
185995
  function jsonValueTargetsKodyVirtualModule(value) {
@@ -186044,6 +186147,9 @@ async function prepareKodyGraphFiles(input3) {
186044
186147
  const files = {
186045
186148
  [runtimeModulePath]: createRuntimeModuleSource()
186046
186149
  };
186150
+ const moduleRoles2 = /* @__PURE__ */ new Map([
186151
+ [runtimeModulePath, "runtime"]
186152
+ ]);
186047
186153
  const rootPackage = readRootPackage(input3.sourceFiles);
186048
186154
  const entryPoint = resolveWorkspaceSourceFilePath({
186049
186155
  files: input3.sourceFiles,
@@ -186061,6 +186167,7 @@ async function prepareKodyGraphFiles(input3) {
186061
186167
  baseUrl: input3.baseUrl,
186062
186168
  userId: input3.userId,
186063
186169
  files,
186170
+ moduleRoles: moduleRoles2,
186064
186171
  sourceFiles: input3.sourceFiles,
186065
186172
  rootPackage,
186066
186173
  rootPackageId: input3.rootPackageId?.trim() || null,
@@ -186079,8 +186186,10 @@ async function prepareKodyGraphFiles(input3) {
186079
186186
  }
186080
186187
  if (isBundlerRootConfigPath(normalizedSourcePath)) {
186081
186188
  files[normalizedSourcePath] = content;
186189
+ moduleRoles2.set(normalizedSourcePath, "root-config");
186082
186190
  }
186083
186191
  if (isBundlerRootDependencyPath(normalizedSourcePath)) {
186192
+ moduleRoles2.set(normalizedSourcePath, "root-dependency");
186084
186193
  files[normalizedSourcePath] = bundlerScriptSourcePathPattern.test(normalizedSourcePath) && !isTypeDeclarationFilePath(normalizedSourcePath) ? await rewriteKodyImports({
186085
186194
  state: state2,
186086
186195
  source: content,
@@ -186090,13 +186199,15 @@ async function prepareKodyGraphFiles(input3) {
186090
186199
  continue;
186091
186200
  }
186092
186201
  const normalizedPath = joinPath(rootSourcePrefix, normalizedSourcePath);
186093
- if (normalizedSourcePath === packageManifestPath3) {
186202
+ if (normalizedSourcePath === packageManifestPath2) {
186094
186203
  files[normalizedPath] = content;
186204
+ moduleRoles2.set(normalizedPath, "root-source");
186095
186205
  continue;
186096
186206
  }
186097
186207
  if (!reachableRootFiles.has(normalizedSourcePath)) {
186098
186208
  continue;
186099
186209
  }
186210
+ moduleRoles2.set(normalizedPath, "root-source");
186100
186211
  if (isTypeDeclarationFilePath(normalizedSourcePath)) {
186101
186212
  files[normalizedPath] = content;
186102
186213
  continue;
@@ -186110,6 +186221,7 @@ async function prepareKodyGraphFiles(input3) {
186110
186221
  }
186111
186222
  return {
186112
186223
  files: refreshKodyRuntimeModules(files),
186224
+ moduleRoles: moduleRoles2,
186113
186225
  packages: state2.packages,
186114
186226
  publishedArtifactDependencies: state2.publishedArtifactDependencies,
186115
186227
  entryPoint
@@ -187848,12 +187960,12 @@ var init_connection_trouble = __esm({
187848
187960
  });
187849
187961
 
187850
187962
  // ../worker/src/mcp/secrets/crypto.ts
187851
- var textEncoder2, textDecoder;
187963
+ var textEncoder3, textDecoder;
187852
187964
  var init_crypto = __esm({
187853
187965
  "../worker/src/mcp/secrets/crypto.ts"() {
187854
187966
  "use strict";
187855
187967
  init_base64();
187856
- textEncoder2 = new TextEncoder();
187968
+ textEncoder3 = new TextEncoder();
187857
187969
  textDecoder = new TextDecoder();
187858
187970
  }
187859
187971
  });
@@ -199495,6 +199607,9 @@ var init_db = __esm({
199495
199607
  utm_term: column.text(),
199496
199608
  first_touch_landing_path: column.text(),
199497
199609
  first_touch_referrer: column.text(),
199610
+ whats_new_email_opt_in: column.integer(),
199611
+ whats_new_email_opt_in_updated_at: column.text(),
199612
+ whats_new_email_opt_in_source: column.text(),
199498
199613
  first_mcp_connected_at: column.text(),
199499
199614
  first_execute_at: column.text(),
199500
199615
  first_search_at: column.text(),