@zuplo/cli 7.9.17 → 7.9.19

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 (53) hide show
  1. package/dist/source/ai-gateway/catalog.json +170 -1
  2. package/dist/source/ai-gateway/planner.test.js +49 -1
  3. package/dist/source/ai-gateway/planner.test.js.map +1 -1
  4. package/node_modules/@posthog/core/dist/error-tracking/chunk-ids.d.ts.map +1 -1
  5. package/node_modules/@posthog/core/dist/error-tracking/chunk-ids.js +36 -22
  6. package/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs +36 -22
  7. package/node_modules/@posthog/core/dist/error-tracking/release.d.ts +3 -5
  8. package/node_modules/@posthog/core/dist/error-tracking/release.d.ts.map +1 -1
  9. package/node_modules/@posthog/core/dist/error-tracking/release.js +4 -0
  10. package/node_modules/@posthog/core/dist/error-tracking/release.mjs +4 -0
  11. package/node_modules/@posthog/core/dist/featureFlagUtils.d.ts.map +1 -1
  12. package/node_modules/@posthog/core/dist/featureFlagUtils.js +1 -2
  13. package/node_modules/@posthog/core/dist/featureFlagUtils.mjs +1 -2
  14. package/node_modules/@posthog/core/package.json +2 -2
  15. package/node_modules/@posthog/core/src/error-tracking/chunk-ids.spec.ts +77 -0
  16. package/node_modules/@posthog/core/src/error-tracking/chunk-ids.ts +50 -25
  17. package/node_modules/@posthog/core/src/error-tracking/release.spec.ts +34 -0
  18. package/node_modules/@posthog/core/src/error-tracking/release.ts +10 -5
  19. package/node_modules/@posthog/core/src/featureFlagUtils.ts +0 -2
  20. package/node_modules/@zuplo/core/customer.cli.minified.js +1 -1
  21. package/node_modules/@zuplo/core/index.minified.js +1 -1
  22. package/node_modules/@zuplo/core/package.json +1 -1
  23. package/node_modules/@zuplo/graphql/package.json +1 -1
  24. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  25. package/node_modules/@zuplo/otel/package.json +1 -1
  26. package/node_modules/@zuplo/runtime/out/esm/{chunk-UJ56MYSD.js → chunk-6YPRGG62.js} +108 -107
  27. package/node_modules/@zuplo/runtime/out/esm/chunk-6YPRGG62.js.map +1 -0
  28. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  29. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  30. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  31. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
  32. package/node_modules/@zuplo/runtime/out/types/index.d.ts +122 -10
  33. package/node_modules/@zuplo/runtime/package.json +1 -1
  34. package/node_modules/content-disposition/README.md +105 -35
  35. package/node_modules/content-disposition/dist/index.d.ts +72 -0
  36. package/node_modules/content-disposition/dist/index.js +388 -0
  37. package/node_modules/content-disposition/dist/index.js.map +1 -0
  38. package/node_modules/content-disposition/package.json +31 -19
  39. package/node_modules/express/Readme.md +15 -9
  40. package/node_modules/express/lib/application.js +2 -2
  41. package/node_modules/express/lib/request.js +32 -19
  42. package/node_modules/express/lib/response.js +27 -30
  43. package/node_modules/express/node_modules/content-type/LICENSE +22 -0
  44. package/node_modules/express/node_modules/content-type/README.md +71 -0
  45. package/node_modules/express/node_modules/content-type/dist/index.d.ts +46 -0
  46. package/node_modules/express/node_modules/content-type/dist/index.js +176 -0
  47. package/node_modules/express/node_modules/content-type/dist/index.js.map +1 -0
  48. package/node_modules/express/node_modules/content-type/package.json +52 -0
  49. package/node_modules/express/package.json +10 -10
  50. package/package.json +11 -11
  51. package/node_modules/@zuplo/runtime/out/esm/chunk-UJ56MYSD.js.map +0 -1
  52. package/node_modules/content-disposition/index.js +0 -536
  53. /package/node_modules/@zuplo/runtime/out/esm/{chunk-UJ56MYSD.js.LEGAL.txt → chunk-6YPRGG62.js.LEGAL.txt} +0 -0
@@ -1,34 +1,48 @@
1
1
  let parsedStackResults;
2
- let lastKeysCount;
2
+ let lastPostHogChunkIds;
3
+ let lastNativeDebugIds;
3
4
  let cachedFilenameChunkIds;
4
5
  function getFilenameToChunkIdMap(stackParser) {
5
- const chunkIdMap = globalThis._posthogChunkIds;
6
- if (!chunkIdMap) return;
7
- const chunkIdKeys = Object.keys(chunkIdMap);
8
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;
9
- lastKeysCount = chunkIdKeys.length;
10
- cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{
11
- if (!parsedStackResults) parsedStackResults = {};
12
- const result = parsedStackResults[stackKey];
13
- if (result) acc[result[0]] = result[1];
14
- else {
6
+ const posthogChunkIds = globalThis._posthogChunkIds;
7
+ const nativeDebugIds = globalThis._debugIds;
8
+ if (!posthogChunkIds && !nativeDebugIds) return;
9
+ const posthogKeys = posthogChunkIds ? Object.keys(posthogChunkIds) : [];
10
+ const nativeKeys = nativeDebugIds ? Object.keys(nativeDebugIds) : [];
11
+ if (cachedFilenameChunkIds && matchesSnapshot(posthogChunkIds, posthogKeys, lastPostHogChunkIds) && matchesSnapshot(nativeDebugIds, nativeKeys, lastNativeDebugIds)) return cachedFilenameChunkIds;
12
+ lastPostHogChunkIds = posthogChunkIds ? {
13
+ ...posthogChunkIds
14
+ } : void 0;
15
+ lastNativeDebugIds = nativeDebugIds ? {
16
+ ...nativeDebugIds
17
+ } : void 0;
18
+ cachedFilenameChunkIds = {};
19
+ parsedStackResults ??= {};
20
+ const addChunkIds = (keys, chunkIds)=>{
21
+ for (const stackKey of keys){
22
+ const chunkId = chunkIds[stackKey];
23
+ if (!chunkId) continue;
24
+ const cachedFilename = parsedStackResults?.[stackKey];
25
+ if (cachedFilename) {
26
+ cachedFilenameChunkIds[cachedFilename] = chunkId;
27
+ continue;
28
+ }
15
29
  const parsedStack = stackParser(stackKey);
16
30
  for(let i = parsedStack.length - 1; i >= 0; i--){
17
- const stackFrame = parsedStack[i];
18
- const filename = stackFrame?.filename;
19
- const chunkId = chunkIdMap[stackKey];
20
- if (filename && chunkId) {
21
- acc[filename] = chunkId;
22
- parsedStackResults[stackKey] = [
23
- filename,
24
- chunkId
25
- ];
31
+ const filename = parsedStack[i]?.filename;
32
+ if (filename) {
33
+ cachedFilenameChunkIds[filename] = chunkId;
34
+ parsedStackResults[stackKey] = filename;
26
35
  break;
27
36
  }
28
37
  }
29
38
  }
30
- return acc;
31
- }, {});
39
+ };
40
+ if (nativeDebugIds) addChunkIds(nativeKeys, nativeDebugIds);
41
+ if (posthogChunkIds) addChunkIds(posthogKeys, posthogChunkIds);
32
42
  return cachedFilenameChunkIds;
33
43
  }
44
+ function matchesSnapshot(chunkIds, keys, snapshot) {
45
+ if (!chunkIds || !snapshot) return chunkIds === snapshot;
46
+ return keys.length === Object.keys(snapshot).length && keys.every((key)=>chunkIds[key] === snapshot[key]);
47
+ }
34
48
  export { getFilenameToChunkIdMap };
@@ -1,10 +1,8 @@
1
1
  /**
2
- * Read the release id injected into the bundle by posthog-cli.
2
+ * Read the release id embedded at build time or injected into a processed bundle.
3
3
  *
4
- * The CLI prepends a small IIFE to each chunk that sets `globalThis._posthogReleaseId` to the
5
- * release row's id (a string, first write wins so the first loaded chunk pins the release for the
6
- * runtime). The SDK emits it on `$exception` events so the server resolves the release with a plain
7
- * foreign-key lookup. Returns `undefined` when nothing was injected or the value is malformed.
4
+ * Framework integrations can compile `POSTHOG_RELEASE_ID` into browser code before asset hashes
5
+ * are finalized. The global remains as a fallback for bundles processed by posthog-cli.
8
6
  */
9
7
  export declare function getInjectedReleaseId(): string | undefined;
10
8
  //# sourceMappingURL=release.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"release.d.ts","sourceRoot":"","sources":["../../src/error-tracking/release.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAGzD"}
1
+ {"version":3,"file":"release.d.ts","sourceRoot":"","sources":["../../src/error-tracking/release.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAUzD"}
@@ -28,6 +28,10 @@ var __webpack_require__ = {};
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  function getInjectedReleaseId() {
31
+ if ("u" > typeof process) {
32
+ const fromEnvironment = process.env.POSTHOG_RELEASE_ID?.trim();
33
+ if (fromEnvironment) return fromEnvironment;
34
+ }
31
35
  const injected = globalThis._posthogReleaseId;
32
36
  return 'string' == typeof injected && injected.length > 0 ? injected : void 0;
33
37
  }
@@ -1,4 +1,8 @@
1
1
  function getInjectedReleaseId() {
2
+ if ("u" > typeof process) {
3
+ const fromEnvironment = process.env.POSTHOG_RELEASE_ID?.trim();
4
+ if (fromEnvironment) return fromEnvironment;
5
+ }
2
6
  const injected = globalThis._posthogReleaseId;
3
7
  return 'string' == typeof injected && injected.length > 0 ? injected : void 0;
4
8
  }
@@ -1 +1 @@
1
- {"version":3,"file":"featureFlagUtils.d.ts","sourceRoot":"","sources":["../src/featureFlagUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAEhB,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,EAEtB,mBAAmB,EACnB,2BAA2B,EAC5B,MAAM,SAAS,CAAA;AAEhB,eAAO,MAAM,sBAAsB,kBAE7B,mBAAmB,CAAC,sBAAsB,EAAE,OAAO,CAAC,GACpD,mBAAmB,CAAC,sBAAsB,EAAE,cAAc,GAAG,qBAAqB,CAAC,KACtF,2BAgCF,CAAA;AAqBD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,UAAW,oBAAoB,CAAC,OAAO,CAAC,KAAG,oBAAoB,CAAC,cAAc,CAMhH,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,UACxB,oBAAoB,CAAC,OAAO,CAAC,KACnC,oBAAoB,CAAC,qBAAqB,CAa5C,CAAA;AAED,eAAO,MAAM,mBAAmB,WAAY,iBAAiB,GAAG,SAAS,KAAG,gBAAgB,GAAG,SAE9F,CAAA;AAED,eAAO,MAAM,YAAY,aAAc,GAAG,KAAG,GAU5C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,uCAAuC,iBACpC,sBAAsB,CAAC,cAAc,CAAC,uBAC/B,sBAAsB,CAAC,qBAAqB,CAAC,KACjE,2BAaF,CAAA;AAED,eAAO,MAAM,eAAe,SAAU,iBAAiB,SAAS,gBAAgB,KAAG,iBAMlF,CAAA;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAEpE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,GAAG,SAAS,CAE/E;AAED,eAAO,MAAM,oBAAoB,gBAAiB,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,KAAG,iBAAiB,EAWtG,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,6CAA6C,YACxD,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,aAAa,EACb,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,MAAM,EACN,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,KAAK,CACG,CAAA;AAEV,eAAO,MAAM,oCAAoC,EAAE,SAAS,MAAM,EAqCjE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iCAAiC,eAChC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,kBAChB,SAAS,MAAM,EAAE,KAC/B,MAAM,CAAC,MAAM,EAAE,GAAG,CAUpB,CAAA"}
1
+ {"version":3,"file":"featureFlagUtils.d.ts","sourceRoot":"","sources":["../src/featureFlagUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAEhB,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,EAEtB,mBAAmB,EACnB,2BAA2B,EAC5B,MAAM,SAAS,CAAA;AAEhB,eAAO,MAAM,sBAAsB,kBAE7B,mBAAmB,CAAC,sBAAsB,EAAE,OAAO,CAAC,GACpD,mBAAmB,CAAC,sBAAsB,EAAE,cAAc,GAAG,qBAAqB,CAAC,KACtF,2BAgCF,CAAA;AAqBD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,UAAW,oBAAoB,CAAC,OAAO,CAAC,KAAG,oBAAoB,CAAC,cAAc,CAMhH,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,UACxB,oBAAoB,CAAC,OAAO,CAAC,KACnC,oBAAoB,CAAC,qBAAqB,CAa5C,CAAA;AAED,eAAO,MAAM,mBAAmB,WAAY,iBAAiB,GAAG,SAAS,KAAG,gBAAgB,GAAG,SAE9F,CAAA;AAED,eAAO,MAAM,YAAY,aAAc,GAAG,KAAG,GAU5C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,uCAAuC,iBACpC,sBAAsB,CAAC,cAAc,CAAC,uBAC/B,sBAAsB,CAAC,qBAAqB,CAAC,KACjE,2BAaF,CAAA;AAED,eAAO,MAAM,eAAe,SAAU,iBAAiB,SAAS,gBAAgB,KAAG,iBAMlF,CAAA;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAEpE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,GAAG,SAAS,CAE/E;AAED,eAAO,MAAM,oBAAoB,gBAAiB,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,KAAG,iBAAiB,EAWtG,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,6CAA6C,YACxD,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,aAAa,EACb,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,MAAM,EACN,OAAO,EACP,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,KAAK,CACG,CAAA;AAEV,eAAO,MAAM,oCAAoC,EAAE,SAAS,MAAM,EAmCjE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iCAAiC,eAChC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,kBAChB,SAAS,MAAM,EAAE,KAC/B,MAAM,CAAC,MAAM,EAAE,GAAG,CAUpB,CAAA"}
@@ -180,8 +180,7 @@ const MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
180
180
  '$lib',
181
181
  '$lib_version',
182
182
  '$device_id',
183
- '$is_server',
184
- '$react_native_version'
183
+ '$is_server'
185
184
  ];
186
185
  const minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{
187
186
  const minimal = {};
@@ -151,8 +151,7 @@ const MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
151
151
  '$lib',
152
152
  '$lib_version',
153
153
  '$device_id',
154
- '$is_server',
155
- '$react_native_version'
154
+ '$is_server'
156
155
  ];
157
156
  const minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{
158
157
  const minimal = {};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/core",
3
- "version": "1.57.2",
3
+ "version": "1.57.4",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
@@ -71,7 +71,7 @@
71
71
  }
72
72
  },
73
73
  "dependencies": {
74
- "@posthog/types": "^1.415.1"
74
+ "@posthog/types": "^1.415.2"
75
75
  },
76
76
  "devDependencies": {
77
77
  "@rslib/core": "0.23.2",
@@ -0,0 +1,77 @@
1
+ import type { StackParser } from './types'
2
+
3
+ const stackParser: StackParser = (stack) => [
4
+ {
5
+ platform: 'web:javascript',
6
+ filename: stack.split('|')[0],
7
+ },
8
+ ]
9
+
10
+ describe('getFilenameToChunkIdMap', () => {
11
+ beforeEach(() => {
12
+ vi.resetModules()
13
+ delete (globalThis as any)._posthogChunkIds
14
+ delete (globalThis as any)._debugIds
15
+ })
16
+
17
+ afterEach(() => {
18
+ delete (globalThis as any)._posthogChunkIds
19
+ delete (globalThis as any)._debugIds
20
+ })
21
+
22
+ it('maps native debug IDs to filenames', async () => {
23
+ ;(globalThis as any)._debugIds = {
24
+ 'https://example.com/chunk.js|native': 'native-debug-id',
25
+ }
26
+ const { getFilenameToChunkIdMap } = await import('./chunk-ids')
27
+
28
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({
29
+ 'https://example.com/chunk.js': 'native-debug-id',
30
+ })
31
+ })
32
+
33
+ it('prefers PostHog chunk IDs over native debug IDs for the same file', async () => {
34
+ ;(globalThis as any)._debugIds = {
35
+ 'https://example.com/chunk.js|native': 'native-debug-id',
36
+ }
37
+ ;(globalThis as any)._posthogChunkIds = {
38
+ 'https://example.com/chunk.js|posthog': 'posthog-chunk-id',
39
+ }
40
+ const { getFilenameToChunkIdMap } = await import('./chunk-ids')
41
+
42
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({
43
+ 'https://example.com/chunk.js': 'posthog-chunk-id',
44
+ })
45
+ })
46
+
47
+ it('refreshes the cached map when native debug IDs are added', async () => {
48
+ ;(globalThis as any)._debugIds = {
49
+ 'https://example.com/one.js|native': 'one',
50
+ }
51
+ const { getFilenameToChunkIdMap } = await import('./chunk-ids')
52
+
53
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({ 'https://example.com/one.js': 'one' })
54
+
55
+ ;(globalThis as any)._debugIds['https://example.com/two.js|native'] = 'two'
56
+
57
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({
58
+ 'https://example.com/one.js': 'one',
59
+ 'https://example.com/two.js': 'two',
60
+ })
61
+ })
62
+
63
+ it('refreshes the cached map when a debug ID map is replaced with the same number of entries', async () => {
64
+ ;(globalThis as any)._debugIds = {
65
+ 'https://example.com/one.js|native': 'one',
66
+ }
67
+ const { getFilenameToChunkIdMap } = await import('./chunk-ids')
68
+
69
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({ 'https://example.com/one.js': 'one' })
70
+
71
+ ;(globalThis as any)._debugIds = {
72
+ 'https://example.com/two.js|native': 'two',
73
+ }
74
+
75
+ expect(getFilenameToChunkIdMap(stackParser)).toEqual({ 'https://example.com/two.js': 'two' })
76
+ })
77
+ })
@@ -5,55 +5,80 @@
5
5
  import type { StackParser } from './types'
6
6
 
7
7
  type StackString = string
8
- type CachedResult = [string, string]
8
+ type CachedResult = string
9
9
 
10
10
  type ChunkIdMapType = Record<string, string>
11
11
 
12
12
  let parsedStackResults: Record<StackString, CachedResult> | undefined
13
- let lastKeysCount: number | undefined
13
+ let lastPostHogChunkIds: ChunkIdMapType | undefined
14
+ let lastNativeDebugIds: ChunkIdMapType | undefined
14
15
  let cachedFilenameChunkIds: ChunkIdMapType | undefined
15
16
 
16
17
  export function getFilenameToChunkIdMap(stackParser: StackParser): ChunkIdMapType | undefined {
17
- const chunkIdMap = (globalThis as any)._posthogChunkIds as ChunkIdMapType | undefined
18
- if (!chunkIdMap) {
18
+ const posthogChunkIds = (globalThis as any)._posthogChunkIds as ChunkIdMapType | undefined
19
+ const nativeDebugIds = (globalThis as any)._debugIds as ChunkIdMapType | undefined
20
+ if (!posthogChunkIds && !nativeDebugIds) {
19
21
  return undefined
20
22
  }
21
23
 
22
- const chunkIdKeys = Object.keys(chunkIdMap)
24
+ const posthogKeys = posthogChunkIds ? Object.keys(posthogChunkIds) : []
25
+ const nativeKeys = nativeDebugIds ? Object.keys(nativeDebugIds) : []
23
26
 
24
- if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) {
27
+ if (
28
+ cachedFilenameChunkIds &&
29
+ matchesSnapshot(posthogChunkIds, posthogKeys, lastPostHogChunkIds) &&
30
+ matchesSnapshot(nativeDebugIds, nativeKeys, lastNativeDebugIds)
31
+ ) {
25
32
  return cachedFilenameChunkIds
26
33
  }
27
34
 
28
- lastKeysCount = chunkIdKeys.length
35
+ lastPostHogChunkIds = posthogChunkIds ? { ...posthogChunkIds } : undefined
36
+ lastNativeDebugIds = nativeDebugIds ? { ...nativeDebugIds } : undefined
37
+ cachedFilenameChunkIds = {}
38
+ parsedStackResults ??= {}
29
39
 
30
- cachedFilenameChunkIds = chunkIdKeys.reduce<Record<string, string>>((acc, stackKey) => {
31
- if (!parsedStackResults) {
32
- parsedStackResults = {}
33
- }
40
+ const addChunkIds = (keys: string[], chunkIds: ChunkIdMapType): void => {
41
+ for (const stackKey of keys) {
42
+ const chunkId = chunkIds[stackKey]
43
+ if (!chunkId) {
44
+ continue
45
+ }
34
46
 
35
- const result = parsedStackResults[stackKey]
47
+ const cachedFilename = parsedStackResults?.[stackKey]
48
+ if (cachedFilename) {
49
+ cachedFilenameChunkIds![cachedFilename] = chunkId
50
+ continue
51
+ }
36
52
 
37
- if (result) {
38
- acc[result[0]] = result[1]
39
- } else {
40
53
  const parsedStack = stackParser(stackKey)
41
-
42
54
  for (let i = parsedStack.length - 1; i >= 0; i--) {
43
- const stackFrame = parsedStack[i]
44
- const filename = stackFrame?.filename
45
- const chunkId = chunkIdMap[stackKey]
46
-
47
- if (filename && chunkId) {
48
- acc[filename] = chunkId
49
- parsedStackResults[stackKey] = [filename, chunkId]
55
+ const filename = parsedStack[i]?.filename
56
+ if (filename) {
57
+ cachedFilenameChunkIds![filename] = chunkId
58
+ parsedStackResults![stackKey] = filename
50
59
  break
51
60
  }
52
61
  }
53
62
  }
63
+ }
54
64
 
55
- return acc
56
- }, {})
65
+ if (nativeDebugIds) {
66
+ addChunkIds(nativeKeys, nativeDebugIds)
67
+ }
68
+ if (posthogChunkIds) {
69
+ addChunkIds(posthogKeys, posthogChunkIds)
70
+ }
57
71
 
58
72
  return cachedFilenameChunkIds
59
73
  }
74
+
75
+ function matchesSnapshot(
76
+ chunkIds: ChunkIdMapType | undefined,
77
+ keys: string[],
78
+ snapshot: ChunkIdMapType | undefined
79
+ ): boolean {
80
+ if (!chunkIds || !snapshot) {
81
+ return chunkIds === snapshot
82
+ }
83
+ return keys.length === Object.keys(snapshot).length && keys.every((key) => chunkIds[key] === snapshot[key])
84
+ }
@@ -0,0 +1,34 @@
1
+ import { getInjectedReleaseId } from './release'
2
+
3
+ describe('getInjectedReleaseId', () => {
4
+ const originalReleaseId = process.env.POSTHOG_RELEASE_ID
5
+
6
+ afterEach(() => {
7
+ if (originalReleaseId === undefined) {
8
+ delete process.env.POSTHOG_RELEASE_ID
9
+ } else {
10
+ process.env.POSTHOG_RELEASE_ID = originalReleaseId
11
+ }
12
+ delete (globalThis as any)._posthogReleaseId
13
+ })
14
+
15
+ it('reads and trims POSTHOG_RELEASE_ID', () => {
16
+ process.env.POSTHOG_RELEASE_ID = ' release-from-environment '
17
+
18
+ expect(getInjectedReleaseId()).toBe('release-from-environment')
19
+ })
20
+
21
+ it('prefers POSTHOG_RELEASE_ID over the injected global', () => {
22
+ process.env.POSTHOG_RELEASE_ID = 'release-from-environment'
23
+ ;(globalThis as any)._posthogReleaseId = 'release-from-injection'
24
+
25
+ expect(getInjectedReleaseId()).toBe('release-from-environment')
26
+ })
27
+
28
+ it('falls back to the injected global when the environment value is empty', () => {
29
+ process.env.POSTHOG_RELEASE_ID = ' '
30
+ ;(globalThis as any)._posthogReleaseId = 'release-from-injection'
31
+
32
+ expect(getInjectedReleaseId()).toBe('release-from-injection')
33
+ })
34
+ })
@@ -1,12 +1,17 @@
1
1
  /**
2
- * Read the release id injected into the bundle by posthog-cli.
2
+ * Read the release id embedded at build time or injected into a processed bundle.
3
3
  *
4
- * The CLI prepends a small IIFE to each chunk that sets `globalThis._posthogReleaseId` to the
5
- * release row's id (a string, first write wins so the first loaded chunk pins the release for the
6
- * runtime). The SDK emits it on `$exception` events so the server resolves the release with a plain
7
- * foreign-key lookup. Returns `undefined` when nothing was injected or the value is malformed.
4
+ * Framework integrations can compile `POSTHOG_RELEASE_ID` into browser code before asset hashes
5
+ * are finalized. The global remains as a fallback for bundles processed by posthog-cli.
8
6
  */
9
7
  export function getInjectedReleaseId(): string | undefined {
8
+ if (typeof process !== 'undefined') {
9
+ const fromEnvironment = process.env.POSTHOG_RELEASE_ID?.trim()
10
+ if (fromEnvironment) {
11
+ return fromEnvironment
12
+ }
13
+ }
14
+
10
15
  const injected = (globalThis as any)._posthogReleaseId
11
16
  return typeof injected === 'string' && injected.length > 0 ? injected : undefined
12
17
  }
@@ -252,8 +252,6 @@ export const MINIMAL_FLAG_CALLED_EVENT_PROPERTIES: readonly string[] = [
252
252
  '$lib_version',
253
253
  '$device_id',
254
254
  '$is_server',
255
- // Runtime identity, kept for runtime breakdowns of flag calls
256
- '$react_native_version',
257
255
  ]
258
256
 
259
257
  /**
@@ -572,7 +572,7 @@ globstar while`,s,le,o,se,tt),this.matchOne(s.slice(le),o.slice(se),f))return th
572
572
  `),stderr:E.join(`
573
573
  `),exitCode:A},"Tar process logs")}}t(JXt,"tarFolder");async function $Xt({tarFilePath:s,outputDir:o,logger:f}){let d=[],y=[],E;try{await new Promise((A,R)=>{let q=sit("sh",["-c",`tar -xvf ${s} -C ${o};`]);q.stdout.on("data",K=>{let ye=K.toString().trim();ye.length>0&&d.push(ye.trim())}),q.stderr.on("data",K=>{let ye=K.toString().trim();ye.length>0&&y.push(ye.trim())}),q.on("close",K=>{E=K,K===0?A():R(new Error(`tar process exited with code ${K}`))}),q.on("error",K=>{R(K)})})}catch(A){throw new Error("Failed to untar file",{cause:A})}finally{f.info({stdout:d.join(`
574
574
  `),stderr:y.join(`
575
- `),exitCode:E},"Untar process logs")}}t($Xt,"untarFile");async function WXt(s){if(await QPe(s))return await qN.rm(s,{recursive:!0})}t(WXt,"deleteFolder");var nu=eAe;var Qct=wp(Dst(),1);import{AssertionError as ger}from"node:assert";function UP(s,o){if(s===!1)throw new ger({message:o})}t(UP,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function zP(s){return s.type===qo.Property}t(zP,"isAstProperty");function FAe(s){return s.type===qo.Array}t(FAe,"isAstArray");function fO(s){return s.type===qo.Literal}t(fO,"isAstLiteral");function GN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(GN,"assertAstObject");import{findNodeAtLocation as yer,getNodeValue as ver,printParseErrorCode as ber,visit as Ser}from"jsonc-parser";var Ter={DEFAULT:{allowTrailingComma:!1}};function JV(s,o=[],f=Ter.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),Ser(s,{onObjectBegin:t((q,K,ye,le)=>{d=E({type:"object",offset:q,length:-1,line:ye+1,column:le+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ye,le,se)=>{d=E({type:"property",offset:K,length:-1,line:le+1,column:se+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ye,line:le,column:se,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ye,le)=>{d=E({type:"array",offset:q,length:-1,line:ye+1,column:le+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ye,le,se)=>{E({type:xer(q),offset:K,length:ye,line:le+1,column:se+1,parent:d,value:q}),y(K+ye)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ye,le,se)=>{o.push({error:q,offset:K,length:ye,line:le+1,column:se+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(JV,"parse");function xer(s){switch(typeof s){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(s){if(Array.isArray(s))return"array"}else return"null";return"object"}default:return"null"}}t(xer,"getNodeType");function G9(s,o){return yer(s,o)}t(G9,"findNodeAtLocation");function $V(s){return ver(s)}t($V,"getNodeValue");function Pst(s){return ber(s)}t(Pst,"printParseErrorCode");var WV=class{static{t(this,"AstAdapter")}parse(o){let d=JV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){UP(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var Eer=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,qV=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=Eer.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import Cer from"node:fs/promises";import{parse as ker}from"@swc/core";var Ast=t(async s=>{let o=new Set;try{let f=await Cer.readFile(s,"utf-8");(await ker(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var Nst=["ai-gateway-akamai-firewall","ai-gateway-auth","ai-gateway-configuration-executor","ai-gateway-configuration-loader","ai-gateway-dlp","ai-gateway-fallback-model","ai-gateway-galileo-tracing","ai-gateway-metering","ai-gateway-model-filtering","ai-gateway-model-override","ai-gateway-opik-tracing","ai-gateway-prompt-injection","ai-gateway-semantic-cache","ai-gateway-smart-router","akamai-firewall-for-ai","prompt-injection","semantic-cache"],Ist={"ai-gateway-akamai-firewall-inbound":"ai-gateway-akamai-firewall","ai-gateway-auth-inbound":"ai-gateway-auth","ai-gateway-auth-v2":"ai-gateway-auth","ai-gateway-auth-v2-inbound":"ai-gateway-auth","ai-gateway-configuration-executor-inbound":"ai-gateway-configuration-executor","ai-gateway-configuration-executor-v2":"ai-gateway-configuration-executor","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor","ai-gateway-configuration-loader-inbound":"ai-gateway-configuration-loader","ai-gateway-configuration-loader-v2":"ai-gateway-configuration-loader","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-inbound":"ai-gateway-fallback-model","ai-gateway-fallback-model-v2":"ai-gateway-fallback-model","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model","ai-gateway-galileo-tracing-inbound":"ai-gateway-galileo-tracing","ai-gateway-metering-inbound":"ai-gateway-metering","ai-gateway-metering-v2":"ai-gateway-metering","ai-gateway-metering-v2-inbound":"ai-gateway-metering","ai-gateway-model-filtering-inbound":"ai-gateway-model-filtering","ai-gateway-model-filtering-v2":"ai-gateway-model-filtering","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering","ai-gateway-model-override-inbound":"ai-gateway-model-override","ai-gateway-opik-tracing-inbound":"ai-gateway-opik-tracing","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-inbound-v2":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache","ai-gateway-smart-router-inbound":"ai-gateway-smart-router","akamai-ai-firewall-inbound-v2":"ai-gateway-akamai-firewall","akamai-ai-firewall-v2":"ai-gateway-akamai-firewall","akamai-ai-firewall-v2-inbound":"ai-gateway-akamai-firewall","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-inbound-v2":"ai-gateway-opik-tracing","comet-opik-tracing-v2":"ai-gateway-opik-tracing","comet-opik-tracing-v2-inbound":"ai-gateway-opik-tracing","galileo-tracing-inbound-v2":"ai-gateway-galileo-tracing","galileo-tracing-v2":"ai-gateway-galileo-tracing","galileo-tracing-v2-inbound":"ai-gateway-galileo-tracing","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Ost={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var LAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var Fst={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var RAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var MAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},toolInputStyle:{enum:["flat","nested"]},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var $ct=wp(Kce(),1),Wct=wp(ele(),1);var tle=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new $ct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Wct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.forEach(y=>{y.keyword==="enum"&&y.params.allowedValues&&Array.isArray(y.params.allowedValues)&&(y.message+=`; ${y.params.allowedValues.join(", ")}`),y.instancePath&&(y.instancePath=y.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ye=A[3],le=Number.isNaN(K)?void 0:f[q][K][ye];E={details:{property:q,index:K,field:ye,fieldValue:le}}}if(y.keyword==="required"&&y.params.missingProperty&&y.instancePath&&(y.message=`A 'path' is missing required property '${y.params.missingProperty}'`),y.keyword==="additionalProperties"&&y.params.additionalProperty&&y.instancePath&&(y.message=`A 'path' should NOT include property '${y.params.additionalProperty}'`),y.keyword==="type"&&y.params.type&&y.instancePath){let q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var iI=tle.instance;iI.addSchema(RAe,"route-configuration.schema.json");iI.addSchema(Fst,"policy-configuration.schema.json");iI.addSchema(LAe,"policies.schema.json");iI.addSchema(MAe,"open-api-route-configuration.schema.json");iI.addSchema(Ost,"fragments.schema.json");var i6r=iI.compile(RAe),qct=iI.compile(MAe),QNe=iI.compile(LAe);var rle=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=QNe(o),this.results}};var nle=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=qct(o),this.results}};import Xor from"node:path";var eIe=/\$import\((.*)\)/,TH=/\$env\((.*?)\)/g;var jk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},Kor=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),qP=t((s,o)=>{if(!s)return!1;let f=Kor(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||zP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var ile=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):FAe(o)?o.children.forEach(f=>{this.visitor(f)}):zP(o)&&this.visitor(o.value)}},Vct=t(s=>{let o=new RegExp(TH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(TH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),Hct=t((s,o,f)=>d=>{if(fO(d)&&typeof d.value=="string"&&d.parent&&FAe(d.parent)){if(!s.some(A=>qP(d.parent,A))){TH.test(d.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Vct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!zP(d)||!fO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>qP(d,E))){TH.test(d.value.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Vct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var xH="config/routes.json",Zor=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],Qor=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Gct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],ecr="handler/{}/options/{}/rewritePattern",tcr="handler/{}/options/{}/baseUrl",sle=class extends ile{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,ecr)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",xH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Yct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,tcr)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",xH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Yct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!zP(o)||!fO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!Qor.some(R=>qP(o,R))&&!Gct.some(R=>qP(o,R))){if(eIe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new jk("An $import() statement is not expected at this location.",xH,o.location,f))}return}let d=eIe.exec(f);if(Gct.some(R=>qP(o,R))&&!d)return;if(!d){this.errors.push(new jk("Invalid $import() statement",xH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=Xor.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=Hct(Zor,this.errors,xH)};function Yct(s){return`(request, context) => {
575
+ `),exitCode:E},"Untar process logs")}}t($Xt,"untarFile");async function WXt(s){if(await QPe(s))return await qN.rm(s,{recursive:!0})}t(WXt,"deleteFolder");var nu=eAe;var Qct=wp(Dst(),1);import{AssertionError as ger}from"node:assert";function UP(s,o){if(s===!1)throw new ger({message:o})}t(UP,"assert");var qo;(function(s){s.Object="Object",s.Property="Property",s.Array="Array",s.Literal="Literal",s.TemplateString="TemplateString",s.Identifier="Identifier",s.FunctionCall="FunctionCall",s.Raw="Raw"})(qo||(qo={}));function H9(s){return s.type===qo.Object}t(H9,"isAstObject");function zP(s){return s.type===qo.Property}t(zP,"isAstProperty");function FAe(s){return s.type===qo.Array}t(FAe,"isAstArray");function fO(s){return s.type===qo.Literal}t(fO,"isAstLiteral");function GN(s){if(s===void 0)throw new Error("Node is undefined");if(!H9(s))throw new Error("Node is not object")}t(GN,"assertAstObject");import{findNodeAtLocation as yer,getNodeValue as ver,printParseErrorCode as ber,visit as Ser}from"jsonc-parser";var Ter={DEFAULT:{allowTrailingComma:!1}};function JV(s,o=[],f=Ter.DEFAULT){let d={type:"array",offset:-1,length:-1,line:-1,column:-1,children:[],parent:void 0};function y(q){d.type==="property"&&(d.length=q-d.offset,d=d.parent)}t(y,"ensurePropertyComplete");function E(q){return d.children?.push(q),q}t(E,"onValue"),Ser(s,{onObjectBegin:t((q,K,ye,le)=>{d=E({type:"object",offset:q,length:-1,line:ye+1,column:le+1,parent:d,children:[]})},"onObjectBegin"),onObjectProperty:t((q,K,ye,le,se)=>{d=E({type:"property",offset:K,length:-1,line:le+1,column:se+1,parent:d,children:[]}),d.children?.push({type:"string",value:q,offset:K,length:ye,line:le,column:se,parent:d})},"onObjectProperty"),onObjectEnd:t((q,K)=>{y(q+K),d.length=q+K-d.offset,d=d.parent,y(q+K)},"onObjectEnd"),onArrayBegin:t((q,K,ye,le)=>{d=E({type:"array",offset:q,length:-1,line:ye+1,column:le+1,parent:d,children:[]})},"onArrayBegin"),onArrayEnd:t((q,K)=>{d.length=q+K-d.offset,d=d.parent,y(q+K)},"onArrayEnd"),onLiteralValue:t((q,K,ye,le,se)=>{E({type:xer(q),offset:K,length:ye,line:le+1,column:se+1,parent:d,value:q}),y(K+ye)},"onLiteralValue"),onSeparator:t((q,K)=>{d.type==="property"&&(q===":"?d.colonOffset=K:q===","&&y(K))},"onSeparator"),onError:t((q,K,ye,le,se)=>{o.push({error:q,offset:K,length:ye,line:le+1,column:se+1})},"onError")},f);let R=d.children?.[0];return R&&delete R.parent,R}t(JV,"parse");function xer(s){switch(typeof s){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(s){if(Array.isArray(s))return"array"}else return"null";return"object"}default:return"null"}}t(xer,"getNodeType");function G9(s,o){return yer(s,o)}t(G9,"findNodeAtLocation");function $V(s){return ver(s)}t($V,"getNodeValue");function Pst(s){return ber(s)}t(Pst,"printParseErrorCode");var WV=class{static{t(this,"AstAdapter")}parse(o){let d=JV(o,[]);if(d)return this.parseNode(d,void 0);throw new Error("Failed to parse JSON")}convert(o){return this.parseNode(o,void 0)}parseNode(o,f){switch(o.type){case"object":return this.createObject(o,f);case"array":return this.createArray(o,f);case"property":return this.createProperty(o,f);case"string":return this.createLiteral(o,f);case"number":return this.createLiteral(o,f);case"boolean":return this.createLiteral(o,f);case"null":return this.createLiteral(o,f)}}createLiteral(o,f){return{type:qo.Literal,location:{line:o.line,column:o.column},parent:f,value:o.type==="null"?null:o.value}}createObject(o,f){let d={type:qo.Object,children:[],parent:f,location:{line:o.line,column:o.column}};return o.children?.forEach(y=>{d.children.push(this.parseNode(y,d))}),d}createProperty(o,f){UP(o.children?.length===2,"Invalid property node");let d={type:qo.Property,location:{line:o.line,column:o.column},parent:f,name:null,value:null};return d.name={value:o.children[0].value,location:{line:o.line,column:o.column},type:qo.Identifier,parent:d},d.value=this.parseNode(o.children[1],d),d}createArray(o,f){let d={type:qo.Array,location:{line:o.line,column:o.column},parent:f,children:[]};return o.children?.forEach(y=>d.children.push(this.parseNode(y,d))),d}};var PS={createLiteral:t((s,o)=>({type:qo.Literal,parent:o,value:s}),"createLiteral"),createTemplateString:t((s,o)=>({type:qo.TemplateString,parent:o,value:s}),"createTemplateString"),createIdentifier:t((s,o)=>({type:qo.Identifier,value:s,parent:o}),"createIdentifier"),createProperty:t((s,o,f)=>{let d={type:qo.Property,parent:f,name:null,value:o};return d.name={value:s,type:qo.Identifier,parent:d},d.value.parent=d,d},"createProperty"),createArrayOfLiterals:t((s,o)=>{let f={type:qo.Array,parent:o,children:[]};for(let d of s)f.children.push(PS.createLiteral(d,f));return f},"createArrayOfLiterals")};var Eer=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,qV=class{static{t(this,"SourceGenerator")}generate(o){let f=[];return this.generateSource(f,o),f.join("")}generateSource(o,f){switch(f.type){case qo.Array:return this.generateArray(o,f);case qo.Object:return this.generateObject(o,f);case qo.Property:return this.generateProperty(o,f);case qo.Literal:return this.generateLiteral(o,f);case qo.FunctionCall:return this.generateFunctionCall(o,f);case qo.Identifier:return this.generateIdentifier(o,f);case qo.Raw:return this.generateRaw(o,f);case qo.TemplateString:return this.generateTemplateString(o,f)}}generateArray(o,f){o.push("["),f.children.map(d=>{this.generateSource(o,d),o.push(",")}),o.push("]")}generateObject(o,f){o.push("{"),f.children.forEach(d=>{this.generateSource(o,d),o.push(",")}),o.push("}")}generateProperty(o,f){this.generateIdentifier(o,f.name),o.push(":"),this.generateSource(o,f.value)}generateFunctionCall(o,f){o.push(f.name.value),o.push("("),f.children.forEach((d,y,E)=>{this.generateSource(o,d),y<E.length&&o.push(",")}),o.push(")")}generateRaw(o,f){o.push(f.value)}generateTemplateString(o,f){o.push("`"),o.push(f.value.replaceAll("`","\\`")),o.push("`")}generateLiteral(o,f){if(f.value===null)return o.push("null");switch(typeof f.value){case"number":case"boolean":return o.push(`${f.value}`);case"string":{let d=f.value,y=JSON.stringify(d);return o.push(`${y}`)}}}generateIdentifier(o,f){let d=Eer.test(f.value)?f.value:`'${f.value}'`;o.push(d)}};import Cer from"node:fs/promises";import{parse as ker}from"@swc/core";var Ast=t(async s=>{let o=new Set;try{let f=await Cer.readFile(s,"utf-8");(await ker(f,{syntax:"typescript"})).body.forEach(y=>{y.type==="ExportDefaultDeclaration"||y.type==="ExportDefaultExpression"?o.add("default"):y.type==="ExportDeclaration"&&y.declaration.type==="FunctionDeclaration"?o.add(y.declaration.identifier.value):y.type==="ExportDeclaration"&&y.declaration.type==="VariableDeclaration"&&y.declaration.declarations[0].id.type==="Identifier"&&o.add(y.declaration.declarations[0].id.value)})}catch{return null}return o},"getJSFileExports");var Nst=["ai-gateway-akamai-firewall","ai-gateway-auth","ai-gateway-configuration-executor","ai-gateway-configuration-loader","ai-gateway-dlp","ai-gateway-fallback-model","ai-gateway-galileo-tracing","ai-gateway-load-balancing","ai-gateway-metering","ai-gateway-model-filtering","ai-gateway-model-override","ai-gateway-opik-tracing","ai-gateway-prompt-injection","ai-gateway-semantic-cache","ai-gateway-smart-router","akamai-firewall-for-ai","prompt-injection","semantic-cache"],Ist={"ai-gateway-akamai-firewall-inbound":"ai-gateway-akamai-firewall","ai-gateway-auth-inbound":"ai-gateway-auth","ai-gateway-auth-v2":"ai-gateway-auth","ai-gateway-auth-v2-inbound":"ai-gateway-auth","ai-gateway-configuration-executor-inbound":"ai-gateway-configuration-executor","ai-gateway-configuration-executor-v2":"ai-gateway-configuration-executor","ai-gateway-configuration-executor-v2-inbound":"ai-gateway-configuration-executor","ai-gateway-configuration-loader-inbound":"ai-gateway-configuration-loader","ai-gateway-configuration-loader-v2":"ai-gateway-configuration-loader","ai-gateway-configuration-loader-v2-inbound":"ai-gateway-configuration-loader","ai-gateway-dlp-inbound":"ai-gateway-dlp","ai-gateway-fallback-model-inbound":"ai-gateway-fallback-model","ai-gateway-fallback-model-v2":"ai-gateway-fallback-model","ai-gateway-fallback-model-v2-inbound":"ai-gateway-fallback-model","ai-gateway-galileo-tracing-inbound":"ai-gateway-galileo-tracing","ai-gateway-load-balancing-inbound":"ai-gateway-load-balancing","ai-gateway-metering-inbound":"ai-gateway-metering","ai-gateway-metering-v2":"ai-gateway-metering","ai-gateway-metering-v2-inbound":"ai-gateway-metering","ai-gateway-model-filtering-inbound":"ai-gateway-model-filtering","ai-gateway-model-filtering-v2":"ai-gateway-model-filtering","ai-gateway-model-filtering-v2-inbound":"ai-gateway-model-filtering","ai-gateway-model-override-inbound":"ai-gateway-model-override","ai-gateway-opik-tracing-inbound":"ai-gateway-opik-tracing","ai-gateway-semantic-cache-inbound":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-inbound-v2":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2":"ai-gateway-semantic-cache","ai-gateway-semantic-cache-v2-inbound":"ai-gateway-semantic-cache","ai-gateway-smart-router-inbound":"ai-gateway-smart-router","akamai-ai-firewall-inbound-v2":"ai-gateway-akamai-firewall","akamai-ai-firewall-v2":"ai-gateway-akamai-firewall","akamai-ai-firewall-v2-inbound":"ai-gateway-akamai-firewall","akamai-firewall-for-ai-inbound":"akamai-firewall-for-ai","akamai-firewall-for-ai-outbound":"akamai-firewall-for-ai","comet-opik-tracing-inbound-v2":"ai-gateway-opik-tracing","comet-opik-tracing-v2":"ai-gateway-opik-tracing","comet-opik-tracing-v2-inbound":"ai-gateway-opik-tracing","galileo-tracing-inbound-v2":"ai-gateway-galileo-tracing","galileo-tracing-v2":"ai-gateway-galileo-tracing","galileo-tracing-v2-inbound":"ai-gateway-galileo-tracing","prompt-injection-outbound":"prompt-injection","semantic-cache-inbound":"semantic-cache"};var Ost={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/fragments.schema.json",$defs:{corsPolicyConfiguration:{type:"object",required:["name","allowedOrigins"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},allowCredentials:{type:"boolean"},maxAge:{type:"number"},allowedOrigins:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},allowedMethods:{oneOf:[{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},{type:"string"}]},allowedHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]},exposeHeaders:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},handlerDefinition:{type:"object",properties:{module:{type:"string",pattern:"^\\$import\\([^ )]*?\\)$"},export:{type:"string"},options:{type:"object",additionalProperties:!0}},additionalProperties:!1,required:["module","export"]},httpMethod:{type:"string",enum:["GET","HEAD","POST","PUT","DELETE","CONNECT","OPTIONS","TRACE","PATCH"]}}};var LAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policies.schema.json",title:"Policies Config File",type:"object",additionalProperties:!1,properties:{policies:{type:"array",items:{$ref:"policy-configuration.schema.json"}},corsPolicies:{type:"array",items:{$ref:"fragments.schema.json#/$defs/corsPolicyConfiguration"}}}};var Fst={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/policy-configuration.schema.json",title:"Policy Configuration Fragment",type:"object",required:["name","policyType","handler"],additionalProperties:!1,properties:{name:{type:"string",pattern:"^[0-9a-z-]+$"},policyType:{type:"string"},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},options:{type:"object",additionalProperties:!0}}};var RAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration.schema.json",title:"Route Configuration Fragment",description:"",type:"object",required:["path","methods","handler"],additionalProperties:!1,$defs:{corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"}},properties:{operationId:{type:"string"},path:{type:"string",pattern:"^/[^\\s]*$"},methods:{type:"array",items:{$ref:"fragments.schema.json#/$defs/httpMethod"}},label:{type:"string",description:"An internal user-friendly identifier of the route."},enforceOpenApi:{type:"boolean",description:"If true, schema validation found in the OpenAPI spec will be enforced on requests/responses."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{$ref:"#/$defs/corsPolicy"},custom:{},mcp:{type:"object",additionalProperties:!1,properties:{enabled:{type:"boolean"}}},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},summary:{type:"string"},description:{type:"string"},excludeFromOpenApi:{type:"boolean"},tags:{type:"array",items:{type:"string"}}}};var MAe={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"http://schemas.zuplo.com/route-configuration-open-api.schema.json",title:"Open API Route Configuration Fragment",description:"These are the properties that can appear under the x-zuplo-route extension in a PathObject in Open API. It's a subset of what can appear in Zuplo's routes.json.",type:"object",required:["handler"],additionalProperties:!1,properties:{label:{type:"string",description:"An internal user-friendly identifier of the route."},key:{type:"string",deprecated:!0},handler:{$ref:"fragments.schema.json#/$defs/handlerDefinition"},corsPolicy:{type:"string",pattern:"^[0-9a-z-]+$"},custom:{},mcp:{oneOf:[{type:"object",additionalProperties:!1,properties:{type:{const:"tool"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"},includeOutputSchema:{type:"boolean"},includeStructuredContent:{type:"boolean"},toolInputStyle:{enum:["flat","nested"]},annotations:{type:"object",additionalProperties:!1,properties:{title:{type:"string"},readOnlyHint:{type:"boolean"},destructiveHint:{type:"boolean"},idempotentHint:{type:"boolean"},openWorldHint:{type:"boolean"}}},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"prompt"},name:{type:"string"},description:{type:"string"},enabled:{type:"boolean"}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"resource"},name:{type:"string"},description:{type:"string"},uri:{type:"string"},mimeType:{type:"string"},enabled:{type:"boolean"},_meta:{type:"object",additionalProperties:!0}},required:["type"]},{type:"object",additionalProperties:!1,properties:{type:{const:"graphql"},enabled:{type:"boolean"},introspectionTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}},executeTool:{type:"object",additionalProperties:!1,properties:{name:{type:"string"},description:{type:"string"}}}},required:["type"]}]},policies:{type:"object",additionalProperties:!1,properties:{inbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}},outbound:{type:"array",items:{type:"string",pattern:"^[0-9a-z-]+$"}}}},tags:{type:"array",items:{type:"string"}}}};var $ct=wp(Kce(),1),Wct=wp(ele(),1);var tle=class s{static{t(this,"JsonValidator")}static#e=new s;static get instance(){return s.#e}ajv;constructor(){this.ajv=new $ct.Ajv2020({allErrors:!0,allowUnionTypes:!0}),this.ajv.addKeyword("faker"),(0,Wct.default)(this.ajv,{mode:"fast"})}addSchema(o,f){this.ajv.addSchema(o,f)}compile(o){let f=this.ajv.compile(o);return t(y=>({isValid:f(y),errors:this.toSimpleErrors(f.errors,y),warnings:[]}),"validator")}toSimpleErrors(o,f){let d=[];return o?.forEach(y=>{y.keyword==="enum"&&y.params.allowedValues&&Array.isArray(y.params.allowedValues)&&(y.message+=`; ${y.params.allowedValues.join(", ")}`),y.instancePath&&(y.instancePath=y.instancePath.replaceAll(/(\/)?(~1)(\/)?/gm,"/"));let E={details:{}},A=y.instancePath.split("/");if(A.length>2){let q=A[1],K=A[2]?parseInt(A[2],10):0,ye=A[3],le=Number.isNaN(K)?void 0:f[q][K][ye];E={details:{property:q,index:K,field:ye,fieldValue:le}}}if(y.keyword==="required"&&y.params.missingProperty&&y.instancePath&&(y.message=`A 'path' is missing required property '${y.params.missingProperty}'`),y.keyword==="additionalProperties"&&y.params.additionalProperty&&y.instancePath&&(y.message=`A 'path' should NOT include property '${y.params.additionalProperty}'`),y.keyword==="type"&&y.params.type&&y.instancePath){let q=y.instancePath.split("/"),K=q[q.length-1];y.message=`Value of property '${K}' must be '${y.params.type}'`}let R=Object.assign(y,E);d.push(R)}),d}};var iI=tle.instance;iI.addSchema(RAe,"route-configuration.schema.json");iI.addSchema(Fst,"policy-configuration.schema.json");iI.addSchema(LAe,"policies.schema.json");iI.addSchema(MAe,"open-api-route-configuration.schema.json");iI.addSchema(Ost,"fragments.schema.json");var i6r=iI.compile(RAe),qct=iI.compile(MAe),QNe=iI.compile(LAe);var rle=class{static{t(this,"PoliciesConfigurationValidator")}results;validate(o){return this.results=QNe(o),this.results}};var nle=class{static{t(this,"OpenAPILocalizedValidator")}results;validate(o){return this.results=qct(o),this.results}};import Xor from"node:path";var eIe=/\$import\((.*)\)/,TH=/\$env\((.*?)\)/g;var jk=class extends Error{static{t(this,"CodeGenError")}location;constructor(o,f,d,y){super(o),this.location={file:f,namespace:"",line:d?d.line:0,column:d?d.column:0,length:0,lineText:y??"",suggestion:""}}},Kor=t(s=>{let o=[],f=s;for(;f.parent;)o.push(f),f=f.parent;return o.reverse()},"invertTree"),qP=t((s,o)=>{if(!s)return!1;let f=Kor(s);return o.split("/").every((E,A)=>{let R=f[A];return R?E==="*"||zP(R)&&R.name.value===E?!0:E==="{}"?R.type===qo.Object:E==="[]"?R.type===qo.Array:!1:!1})},"testPosition");var ile=class{static{t(this,"AstTransformer")}errors=[];transform(o){return this.visitor(o),o}visitor(o){this.visit(o),H9(o)?o.children.forEach(f=>{this.visitor(f)}):FAe(o)?o.children.forEach(f=>{this.visitor(f)}):zP(o)&&this.visitor(o.value)}},Vct=t(s=>{let o=new RegExp(TH).exec(s);if(o?.length===2&&o[0]===s)return{type:"raw",value:`environment["${o[1]}"]`};{let f=s.replaceAll(new RegExp(TH),(d,y)=>`\${environment["${y}"] ? environment["${y}"] : ""}`);if(f!==s)return{type:"template",value:f}}return null},"replaceEnvInString"),Hct=t((s,o,f)=>d=>{if(fO(d)&&typeof d.value=="string"&&d.parent&&FAe(d.parent)){if(!s.some(A=>qP(d.parent,A))){TH.test(d.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value));return}let E=Vct(d.value);if(E){let A=d.parent,R=A.children.indexOf(d);if(R!==-1)if(E.type==="raw"){let q={type:qo.Raw,parent:A,value:E.value};A.children[R]=q}else A.children[R]=PS.createTemplateString(E.value,d)}return}if(!zP(d)||!fO(d.value)||typeof d.value.value!="string")return;if(!s.some(E=>qP(d,E))){TH.test(d.value.value)&&o.push(new jk("An $env() statement is not expected at this location.",f,d.location,d.value.value));return}let y=Vct(d.value.value);if(y)if(y.type==="raw"){let E={type:qo.Raw,parent:null,value:y.value};d.value=E}else d.value=PS.createTemplateString(y.value,d)},"getEnvStatementTransformer");var xH="config/routes.json",Zor=["handler/{}/options/*","handler/{}/options/*/[]","policies/[]/{}/handler/{}/options/*","policies/[]/{}/handler/{}/options/*/[]","corsPolicies/[]/{}/*","corsPolicies/[]/{}/*/[]"],Qor=["handler/{}/module","handler/{}/options/{}/policies/{}/inbound/[]/{}/module","handler/{}/options/{}/policies/{}/outbound/[]/{}/module","handler/{}/options/{}/onOpen/{}/module","policies/[]/{}/handler/{}/module","policies/[]/{}/handler/{}/options/{}/identifier/{}/module","policies/[]/{}/handler/{}/options/{}/validator"],Gct=["handler/{}/options/*","policies/[]/{}/handler/{}/options/*"],ecr="handler/{}/options/{}/rewritePattern",tcr="handler/{}/options/{}/baseUrl",sle=class extends ile{static{t(this,"OpenAPIRoutesFragmentAstTransformer")}importCount=0;addedImports=new Map;getImportName(o){this.addedImports.has(o)||this.addedImports.set(o,`__import${this.importCount++}`);let f=this.addedImports.get(o);if(!f)throw new Error("Import name is undefined. This should not happen.");return f}getImports(){let o=[];return this.addedImports.forEach((f,d)=>{o.push({name:f,path:d})}),o}visit(o){this.rewriteHandlerFunction(o),this.rewriteForwardFunction(o),this.replaceImportStatements(o),this.replaceEnvStatements(o)}rewriteHandlerFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,ecr)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",xH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Yct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}rewriteForwardFunction(o){if(!(!zP(o)||!fO(o.value)||typeof o.value.value!="string")&&qP(o,tcr)){if(!o.parent||!H9(o.parent)){this.errors.push(new jk("Invalid node, expected object",xH,o.parent?o.parent.location:o.location,void 0));return}let f=o.value.value,d={type:qo.Raw,parent:null,value:Yct(f)},y=PS.createProperty("__rewriteFunction",d,o);o.parent.children.push(y)}}replaceImportStatements(o){if(!zP(o)||!fO(o.value))return;let f=o.value.value;if(typeof f!="string")return;if(!Qor.some(R=>qP(o,R))&&!Gct.some(R=>qP(o,R))){if(eIe.test(f)){if(o.name.value==="$ref")return;this.errors.push(new jk("An $import() statement is not expected at this location.",xH,o.location,f))}return}let d=eIe.exec(f);if(Gct.some(R=>qP(o,R))&&!d)return;if(!d){this.errors.push(new jk("Invalid $import() statement",xH,o.location,f));return}let y=d[1];y=y.replace(/\\/g,"/"),y.startsWith(".")&&(y=Xor.posix.join("..",y));let E=this.getImportName(y),A={type:qo.Identifier,parent:o.parent,value:E};o.value=A}replaceEnvStatements=Hct(Zor,this.errors,xH)};function Yct(s){return`(request, context) => {
576
576
  const { params, url, query, method, headers } = request;
577
577
  const { host, hostname, origin, pathname, port, search } = new URL(url);
578
578
  const e = encodeURIComponent;