@cedarjs/internal 5.0.2-rc.5 → 6.0.0-canary.2619

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 (33) hide show
  1. package/dist/build/api-graphql-transforms.d.ts +34 -0
  2. package/dist/build/api-graphql-transforms.d.ts.map +1 -0
  3. package/dist/build/api-graphql-transforms.js +119 -0
  4. package/dist/build/api.d.ts.map +1 -1
  5. package/dist/build/api.js +41 -18
  6. package/dist/build/esbuild-plugin-api-graphql.d.ts +6 -0
  7. package/dist/build/esbuild-plugin-api-graphql.d.ts.map +1 -0
  8. package/dist/build/esbuild-plugin-api-graphql.js +47 -0
  9. package/dist/build/esbuild-plugin-cedar-otel-wrapping.d.ts +13 -0
  10. package/dist/build/esbuild-plugin-cedar-otel-wrapping.d.ts.map +1 -0
  11. package/dist/build/esbuild-plugin-cedar-otel-wrapping.js +180 -0
  12. package/dist/build/esbuild-plugin-handler-als-wrapping.d.ts +4 -0
  13. package/dist/build/esbuild-plugin-handler-als-wrapping.d.ts.map +1 -0
  14. package/dist/build/{esbuild-plugin-cedar-context-wrapping.js → esbuild-plugin-handler-als-wrapping.js} +12 -12
  15. package/dist/cjs/build/api-graphql-transforms.d.ts +34 -0
  16. package/dist/cjs/build/api-graphql-transforms.d.ts.map +1 -0
  17. package/dist/cjs/build/api-graphql-transforms.js +150 -0
  18. package/dist/cjs/build/api.d.ts.map +1 -1
  19. package/dist/cjs/build/api.js +38 -18
  20. package/dist/cjs/build/esbuild-plugin-api-graphql.d.ts +6 -0
  21. package/dist/cjs/build/esbuild-plugin-api-graphql.d.ts.map +1 -0
  22. package/dist/cjs/build/esbuild-plugin-api-graphql.js +75 -0
  23. package/dist/cjs/build/esbuild-plugin-cedar-otel-wrapping.d.ts +13 -0
  24. package/dist/cjs/build/esbuild-plugin-cedar-otel-wrapping.d.ts.map +1 -0
  25. package/dist/cjs/build/esbuild-plugin-cedar-otel-wrapping.js +214 -0
  26. package/dist/cjs/build/esbuild-plugin-handler-als-wrapping.d.ts +4 -0
  27. package/dist/cjs/build/esbuild-plugin-handler-als-wrapping.d.ts.map +1 -0
  28. package/dist/cjs/build/{esbuild-plugin-cedar-context-wrapping.js → esbuild-plugin-handler-als-wrapping.js} +16 -16
  29. package/package.json +21 -9
  30. package/dist/build/esbuild-plugin-cedar-context-wrapping.d.ts +0 -4
  31. package/dist/build/esbuild-plugin-cedar-context-wrapping.d.ts.map +0 -1
  32. package/dist/cjs/build/esbuild-plugin-cedar-context-wrapping.d.ts +0 -4
  33. package/dist/cjs/build/esbuild-plugin-cedar-context-wrapping.d.ts.map +0 -1
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var api_graphql_transforms_exports = {};
30
+ __export(api_graphql_transforms_exports, {
31
+ applyGqlormInject: () => applyGqlormInject,
32
+ applyGraphqlOptionsExtract: () => applyGraphqlOptionsExtract
33
+ });
34
+ module.exports = __toCommonJS(api_graphql_transforms_exports);
35
+ var import_node_fs = __toESM(require("node:fs"), 1);
36
+ var import_node_path = __toESM(require("node:path"), 1);
37
+ var import_oxc_parser = require("oxc-parser");
38
+ var import_project_config = require("@cedarjs/project-config");
39
+ function applyGraphqlOptionsExtract(code) {
40
+ if (code.includes("__cedar_graphqlOptions")) {
41
+ return null;
42
+ }
43
+ const { program } = (0, import_oxc_parser.parseSync)("graphql.ts", code, {
44
+ // lang is only a parse hint; 'ts' also parses JS (the graphql handler can
45
+ // be graphql.js in JS projects), so this is safe for both file types.
46
+ lang: "ts",
47
+ sourceType: "module"
48
+ });
49
+ const importNames = /* @__PURE__ */ new Set();
50
+ for (const node of program.body) {
51
+ if (node.type === "ImportDeclaration") {
52
+ if (node.source.value !== "@cedarjs/graphql-server") {
53
+ continue;
54
+ }
55
+ for (const specifier of node.specifiers) {
56
+ if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "createGraphQLHandler") {
57
+ importNames.add(specifier.local.name);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ if (importNames.size === 0) {
63
+ return null;
64
+ }
65
+ const callExpressionPaths = [];
66
+ new import_oxc_parser.Visitor({
67
+ CallExpression(node) {
68
+ if (node.callee.type === "Identifier" && importNames.has(node.callee.name)) {
69
+ callExpressionPaths.push(node);
70
+ }
71
+ }
72
+ }).visit(program);
73
+ if (callExpressionPaths.length > 1) {
74
+ return null;
75
+ }
76
+ const callExpression = callExpressionPaths[0];
77
+ if (!callExpression) {
78
+ return null;
79
+ }
80
+ const options = callExpression.arguments[0];
81
+ if (!options) {
82
+ return null;
83
+ }
84
+ if (options.type !== "Identifier" && options.type !== "ObjectExpression" && options.type !== "CallExpression" && options.type !== "ConditionalExpression") {
85
+ return null;
86
+ }
87
+ const optionsStart = options.start;
88
+ const optionsEnd = options.end;
89
+ const lineStart = code.lastIndexOf("\n", callExpression.start) + 1;
90
+ const indentMatch = /^[ \t]*/.exec(code.slice(lineStart));
91
+ const indent = indentMatch ? indentMatch[0] : "";
92
+ const optionsConst = `${indent}export const __cedar_graphqlOptions = ${code.slice(
93
+ optionsStart,
94
+ optionsEnd
95
+ )}
96
+ `;
97
+ const before = code.slice(0, lineStart);
98
+ const between = code.slice(lineStart, optionsStart);
99
+ const after = code.slice(optionsEnd);
100
+ return before + optionsConst + between + "__cedar_graphqlOptions" + after;
101
+ }
102
+ function applyGqlormInject(code, id, dbExt = ".ts") {
103
+ if (code.includes("__gqlorm_sdl__")) {
104
+ return null;
105
+ }
106
+ if (!code.includes("createGraphQLHandler")) {
107
+ return null;
108
+ }
109
+ if (!(0, import_project_config.getConfig)().experimental?.gqlorm?.enabled) {
110
+ return null;
111
+ }
112
+ const backendPathWithoutExt = import_node_path.default.join(
113
+ (0, import_project_config.getPaths)().generated.base,
114
+ "gqlorm",
115
+ "backend"
116
+ );
117
+ if (!import_node_fs.default.existsSync(backendPathWithoutExt + ".ts")) {
118
+ return null;
119
+ }
120
+ const handlerPattern = /^export\s+const\s+(\w+)\s*=\s*createGraphQLHandler\s*\(/m;
121
+ const handlerMatch = handlerPattern.exec(code);
122
+ if (!handlerMatch) {
123
+ return null;
124
+ }
125
+ const handlerLineStart = code.lastIndexOf("\n", handlerMatch.index) + 1;
126
+ const relPath = (0, import_project_config.importStatementPath)(
127
+ import_node_path.default.relative(import_node_path.default.dirname(id), backendPathWithoutExt)
128
+ ) + ".ts";
129
+ const dbSrcPath = import_node_path.default.join((0, import_project_config.getPaths)().api.src, "lib", "db");
130
+ const relDbPath = (0, import_project_config.importStatementPath)(import_node_path.default.relative(import_node_path.default.dirname(id), dbSrcPath)) + dbExt;
131
+ const importDb = `import { db as __gqlorm_db__ } from '${relDbPath}'`;
132
+ const importSdl = `import * as __gqlorm_sdl__ from '${relPath}'`;
133
+ const importsToAdd = `${importDb}
134
+ ${importSdl}
135
+ `;
136
+ const sdlsMutation = `Object.assign(sdls, {
137
+ __gqlorm__: {
138
+ schema: __gqlorm_sdl__.schema,
139
+ resolvers: __gqlorm_sdl__.createGqlormResolvers(__gqlorm_db__),
140
+ },
141
+ })
142
+ `;
143
+ const transformed = importsToAdd + code.slice(0, handlerLineStart) + sdlsMutation + code.slice(handlerLineStart);
144
+ return transformed;
145
+ }
146
+ // Annotate the CommonJS export names for ESM import in node:
147
+ 0 && (module.exports = {
148
+ applyGqlormInject,
149
+ applyGraphqlOptionsExtract
150
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/build/api.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAgB,YAAY,EAAe,MAAM,SAAS,CAAA;AAiBtE,eAAO,MAAM,QAAQ,4DAIpB,CAAA;AAED,eAAO,MAAM,UAAU,4DAStB,CAAA;AAED,eAAO,MAAM,aAAa,qBAGzB,CAAA;AA8FD,eAAO,MAAM,gBAAgB,iHAqD5B,CAAA;AAcD,wBAAsB,aAAa,CACjC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAoDf"}
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/build/api.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAgB,YAAY,EAAe,MAAM,SAAS,CAAA;AAuBtE,eAAO,MAAM,QAAQ,4DAIpB,CAAA;AAED,eAAO,MAAM,UAAU,4DAStB,CAAA;AAED,eAAO,MAAM,aAAa,qBAGzB,CAAA;AAuID,eAAO,MAAM,gBAAgB,iHAqD5B,CAAA;AAcD,wBAAsB,aAAa,CACjC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAoDf"}
@@ -42,7 +42,10 @@ var import_vite = require("vite");
42
42
  var import_babel_config = require("@cedarjs/babel-config");
43
43
  var import_project_config = require("@cedarjs/project-config");
44
44
  var import_files = require("../files.js");
45
- var import_esbuild_plugin_cedar_context_wrapping = require("./esbuild-plugin-cedar-context-wrapping.js");
45
+ var import_api_graphql_transforms = require("./api-graphql-transforms.js");
46
+ var import_esbuild_plugin_api_graphql = require("./esbuild-plugin-api-graphql.js");
47
+ var import_esbuild_plugin_cedar_otel_wrapping = require("./esbuild-plugin-cedar-otel-wrapping.js");
48
+ var import_esbuild_plugin_handler_als_wrapping = require("./esbuild-plugin-handler-als-wrapping.js");
46
49
  let BUILD_CTX = null;
47
50
  const buildApi = async () => {
48
51
  BUILD_CTX?.dispose();
@@ -66,24 +69,29 @@ const cleanApiBuild = async () => {
66
69
  const runCedarBabelTransformsPlugin = {
67
70
  name: "cedar-esbuild-babel-transform",
68
71
  setup(build2) {
69
- const cedarConfig = (0, import_project_config.getConfig)();
70
72
  build2.onLoad({ filter: /\.(js|ts|tsx|jsx)$/ }, async (args) => {
71
73
  const fileContents = await import_node_fs.default.promises.readFile(args.path, "utf-8");
72
74
  const transformedCode = await (0, import_babel_config.transformWithBabel)(
73
75
  fileContents,
74
76
  args.path,
75
77
  (0, import_babel_config.getApiSideBabelPlugins)({
76
- openTelemetry: cedarConfig.experimental.opentelemetry.enabled && cedarConfig.experimental.opentelemetry.wrapApi,
77
78
  projectIsEsm: (0, import_project_config.projectSideIsEsm)("api")
78
79
  })
79
80
  );
80
81
  if (transformedCode?.code) {
81
- const functionsDir = (0, import_vite.normalizePath)(
82
- import_node_path.default.join((0, import_project_config.getPaths)().api.src, "functions")
83
- );
84
- const code = (0, import_vite.normalizePath)(args.path).startsWith(functionsDir + "/") ? (0, import_esbuild_plugin_cedar_context_wrapping.applyContextWrapping)(transformedCode.code, {
85
- projectIsEsm: (0, import_project_config.projectSideIsEsm)("api")
86
- }) ?? transformedCode.code : transformedCode.code;
82
+ let code = transformedCode.code;
83
+ const normalizedPath = (0, import_vite.normalizePath)(args.path);
84
+ const cedarPaths = (0, import_project_config.getPaths)();
85
+ const isEsm = (0, import_project_config.projectSideIsEsm)("api");
86
+ const functionsDir = (0, import_vite.normalizePath)(cedarPaths.api.functions);
87
+ if (normalizedPath.startsWith(functionsDir + "/")) {
88
+ code = (0, import_esbuild_plugin_handler_als_wrapping.applyHandlerAlsWrapping)(code, {
89
+ projectIsEsm: isEsm
90
+ }) ?? code;
91
+ }
92
+ if (normalizedPath.startsWith((0, import_vite.normalizePath)(cedarPaths.api.src) + "/")) {
93
+ code = (0, import_esbuild_plugin_cedar_otel_wrapping.applyOtelWrapping)(code, args.path, cedarPaths.api.src) ?? code;
94
+ }
87
95
  return {
88
96
  contents: code,
89
97
  loader: "js"
@@ -110,22 +118,31 @@ function createCedarViteApiPlugin() {
110
118
  if (!(0, import_vite.normalizePath)(id).startsWith((0, import_vite.normalizePath)(cedarPaths.api.base))) {
111
119
  return null;
112
120
  }
121
+ let sourceCode = code;
122
+ const normalizedId = (0, import_vite.normalizePath)(id);
123
+ if (normalizedId.endsWith("/graphql.ts") || normalizedId.endsWith("/graphql.js")) {
124
+ sourceCode = (0, import_api_graphql_transforms.applyGraphqlOptionsExtract)(sourceCode) ?? sourceCode;
125
+ sourceCode = (0, import_api_graphql_transforms.applyGqlormInject)(sourceCode, id) ?? sourceCode;
126
+ }
113
127
  const transformedCode = await (0, import_babel_config.transformWithBabel)(
114
- code,
128
+ sourceCode,
115
129
  id,
116
130
  (0, import_babel_config.getApiSideBabelPlugins)({
117
- openTelemetry: cedarConfig.experimental.opentelemetry.enabled && cedarConfig.experimental.opentelemetry.wrapApi,
118
131
  projectIsEsm: isEsm
119
132
  }),
120
133
  true
121
134
  );
122
135
  if (transformedCode?.code) {
123
- const functionsDir = (0, import_vite.normalizePath)(
124
- import_node_path.default.join(cedarPaths.api.src, "functions")
125
- );
126
- const code2 = (0, import_vite.normalizePath)(id).startsWith(functionsDir + "/") ? (0, import_esbuild_plugin_cedar_context_wrapping.applyContextWrapping)(transformedCode.code, {
127
- projectIsEsm: isEsm
128
- }) ?? transformedCode.code : transformedCode.code;
136
+ let code2 = transformedCode.code;
137
+ if (cedarConfig.experimental?.opentelemetry?.enabled && cedarConfig.experimental?.opentelemetry?.wrapApi) {
138
+ code2 = (0, import_esbuild_plugin_cedar_otel_wrapping.applyOtelWrapping)(code2, id, cedarPaths.api.src) ?? code2;
139
+ }
140
+ const functionsDir = (0, import_vite.normalizePath)(cedarPaths.api.functions);
141
+ if (normalizedId.startsWith(functionsDir + "/")) {
142
+ code2 = (0, import_esbuild_plugin_handler_als_wrapping.applyHandlerAlsWrapping)(code2, {
143
+ projectIsEsm: isEsm
144
+ }) ?? code2;
145
+ }
129
146
  return {
130
147
  code: code2,
131
148
  map: transformedCode.map ?? null
@@ -233,7 +250,10 @@ function getEsbuildOptions(files) {
233
250
  format,
234
251
  allowOverwrite: true,
235
252
  bundle: false,
236
- plugins: [runCedarBabelTransformsPlugin],
253
+ // Registration order matters: cedarApiGraphqlPlugin (narrow filter) must
254
+ // come first so it claims graphql.ts before runCedarBabelTransformsPlugin
255
+ // (broad filter) can. See the NOTE on cedarApiGraphqlPlugin.
256
+ plugins: [import_esbuild_plugin_api_graphql.cedarApiGraphqlPlugin, runCedarBabelTransformsPlugin],
237
257
  outdir: cedarPaths.api.dist,
238
258
  // setting this to 'true' will generate an external sourcemap x.js.map
239
259
  // AND set the sourceMappingURL comment
@@ -0,0 +1,6 @@
1
+ import type { PluginBuild } from 'esbuild';
2
+ export declare const cedarApiGraphqlPlugin: {
3
+ name: string;
4
+ setup(build: PluginBuild): void;
5
+ };
6
+ //# sourceMappingURL=esbuild-plugin-api-graphql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"esbuild-plugin-api-graphql.d.ts","sourceRoot":"","sources":["../../../src/build/esbuild-plugin-api-graphql.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAe1C,eAAO,MAAM,qBAAqB;;iBAEnB,WAAW;CA0DzB,CAAA"}
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var esbuild_plugin_api_graphql_exports = {};
30
+ __export(esbuild_plugin_api_graphql_exports, {
31
+ cedarApiGraphqlPlugin: () => cedarApiGraphqlPlugin
32
+ });
33
+ module.exports = __toCommonJS(esbuild_plugin_api_graphql_exports);
34
+ var import_node_fs = __toESM(require("node:fs"), 1);
35
+ var import_babel_config = require("@cedarjs/babel-config");
36
+ var import_project_config = require("@cedarjs/project-config");
37
+ var import_api_graphql_transforms = require("./api-graphql-transforms.js");
38
+ var import_esbuild_plugin_cedar_otel_wrapping = require("./esbuild-plugin-cedar-otel-wrapping.js");
39
+ var import_esbuild_plugin_handler_als_wrapping = require("./esbuild-plugin-handler-als-wrapping.js");
40
+ const cedarApiGraphqlPlugin = {
41
+ name: "cedar-api-graphql",
42
+ setup(build) {
43
+ build.onLoad({ filter: /[/\\]graphql\.(ts|js)$/ }, async (args) => {
44
+ const cedarConfig = (0, import_project_config.getConfig)();
45
+ let fileContents = await import_node_fs.default.promises.readFile(args.path, "utf-8");
46
+ fileContents = (0, import_api_graphql_transforms.applyGraphqlOptionsExtract)(fileContents) ?? fileContents;
47
+ fileContents = (0, import_api_graphql_transforms.applyGqlormInject)(fileContents, args.path, ".js") ?? fileContents;
48
+ const transformedCode = await (0, import_babel_config.transformWithBabel)(
49
+ fileContents,
50
+ args.path,
51
+ (0, import_babel_config.getApiSideBabelPlugins)({
52
+ projectIsEsm: (0, import_project_config.projectSideIsEsm)("api")
53
+ })
54
+ );
55
+ if (!transformedCode?.code) {
56
+ throw new Error(`Could not transform file: ${args.path}`);
57
+ }
58
+ let code = transformedCode.code;
59
+ if (cedarConfig.experimental?.opentelemetry?.enabled && cedarConfig.experimental?.opentelemetry?.wrapApi) {
60
+ code = (0, import_esbuild_plugin_cedar_otel_wrapping.applyOtelWrapping)(code, args.path, (0, import_project_config.getPaths)().api.src) ?? code;
61
+ }
62
+ code = (0, import_esbuild_plugin_handler_als_wrapping.applyHandlerAlsWrapping)(code, {
63
+ projectIsEsm: (0, import_project_config.projectSideIsEsm)("api")
64
+ }) ?? code;
65
+ return {
66
+ contents: code,
67
+ loader: "js"
68
+ };
69
+ });
70
+ }
71
+ };
72
+ // Annotate the CommonJS export names for ESM import in node:
73
+ 0 && (module.exports = {
74
+ cedarApiGraphqlPlugin
75
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Standalone esbuild equivalent of the Vite cedarOtelWrappingPlugin. Applied
3
+ * inline in the esbuild API build and the standalone-Vite API build so neither
4
+ * path depends on a Babel OTel plugin.
5
+ *
6
+ * For each `export const fn = (async?) (...) => {...}` in an API file, this
7
+ * wraps it with an OpenTelemetry span.
8
+ *
9
+ * Keep this in sync with
10
+ * packages/vite/src/plugins/vite-plugin-cedar-otel-wrapping.ts.
11
+ */
12
+ export declare function applyOtelWrapping(code: string, filename: string, apiSrc: string): string | null;
13
+ //# sourceMappingURL=esbuild-plugin-cedar-otel-wrapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"esbuild-plugin-cedar-otel-wrapping.d.ts","sourceRoot":"","sources":["../../../src/build/esbuild-plugin-cedar-otel-wrapping.ts"],"names":[],"mappings":"AASA;;;;;;;;;;GAUG;AAEH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,MAAM,GAAG,IAAI,CAmFf"}
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var esbuild_plugin_cedar_otel_wrapping_exports = {};
30
+ __export(esbuild_plugin_cedar_otel_wrapping_exports, {
31
+ applyOtelWrapping: () => applyOtelWrapping
32
+ });
33
+ module.exports = __toCommonJS(esbuild_plugin_cedar_otel_wrapping_exports);
34
+ var import_node_path = __toESM(require("node:path"), 1);
35
+ var import_oxc_parser = require("oxc-parser");
36
+ function applyOtelWrapping(code, filename, apiSrc) {
37
+ const relative = import_node_path.default.relative(apiSrc, filename);
38
+ const apiFolder = relative.split(import_node_path.default.sep)[0] ?? "?";
39
+ const parseResult = (0, import_oxc_parser.parseSync)(filename, code, { sourceType: "module" });
40
+ const replacements = [];
41
+ for (const node of parseResult.program.body) {
42
+ if (node.type !== "ExportNamedDeclaration") {
43
+ continue;
44
+ }
45
+ const decl = node.declaration;
46
+ if (decl?.type !== "VariableDeclaration") {
47
+ continue;
48
+ }
49
+ const declarator = decl.declarations[0];
50
+ if (!declarator) {
51
+ continue;
52
+ }
53
+ const fn = declarator.init;
54
+ if (fn?.type !== "ArrowFunctionExpression") {
55
+ continue;
56
+ }
57
+ if (declarator.id.type !== "Identifier") {
58
+ continue;
59
+ }
60
+ const fnName = declarator.id.name;
61
+ const innerArgs = buildInnerArgs(fn.params);
62
+ if (innerArgs === null) {
63
+ continue;
64
+ }
65
+ const fnHeader = code.slice(fn.start, fn.body.start);
66
+ const originalFnSrc = code.slice(fn.start, fn.end);
67
+ const isAsync = fn.async;
68
+ const awaitKw = isAsync ? "await " : "";
69
+ const asyncKw = isAsync ? "async " : "";
70
+ replacements.push({
71
+ start: node.start,
72
+ end: node.end,
73
+ src: buildWrappedExport(
74
+ fnName,
75
+ fnHeader,
76
+ originalFnSrc,
77
+ innerArgs,
78
+ awaitKw,
79
+ asyncKw,
80
+ apiFolder,
81
+ filename
82
+ )
83
+ });
84
+ }
85
+ if (replacements.length === 0) {
86
+ return null;
87
+ }
88
+ let output = code;
89
+ for (let i = replacements.length - 1; i >= 0; i--) {
90
+ const r = replacements[i];
91
+ output = output.slice(0, r.start) + r.src + output.slice(r.end);
92
+ }
93
+ return `import { trace as OTEL_TRACE } from '@opentelemetry/api'
94
+ ` + output;
95
+ }
96
+ function buildInnerArgs(params) {
97
+ const args = [];
98
+ for (const param of params) {
99
+ if (param.type === "RestElement" || param.type === "ArrayPattern" || param.type === "TSParameterProperty") {
100
+ return null;
101
+ }
102
+ if (param.type === "Identifier") {
103
+ args.push(param.name);
104
+ continue;
105
+ }
106
+ if (param.type === "ObjectPattern") {
107
+ for (const prop of param.properties) {
108
+ if (prop.type === "RestElement") {
109
+ return null;
110
+ }
111
+ if (prop.key.type !== "Identifier") {
112
+ return null;
113
+ }
114
+ const value = prop.value;
115
+ if (value.type !== "Identifier" && value.type !== "AssignmentPattern" && value.type !== "ObjectPattern") {
116
+ return null;
117
+ }
118
+ if (value.type === "AssignmentPattern") {
119
+ if (value.left.type !== "Identifier" && value.left.type !== "ObjectPattern") {
120
+ return null;
121
+ }
122
+ }
123
+ }
124
+ const obj = buildObjectCallArg(param);
125
+ if (obj === null) {
126
+ return null;
127
+ }
128
+ args.push(obj);
129
+ continue;
130
+ }
131
+ if (param.type === "AssignmentPattern") {
132
+ const ap = param;
133
+ if (ap.left.type === "Identifier") {
134
+ args.push(ap.left.name);
135
+ } else if (ap.left.type === "ObjectPattern") {
136
+ const obj = buildObjectCallArg(ap.left);
137
+ if (obj === null) {
138
+ return null;
139
+ }
140
+ args.push(obj);
141
+ } else {
142
+ return null;
143
+ }
144
+ continue;
145
+ }
146
+ return null;
147
+ }
148
+ return args.join(", ");
149
+ }
150
+ function buildObjectCallArg(pattern) {
151
+ const keys = [];
152
+ for (const prop of pattern.properties) {
153
+ if (prop.type === "RestElement") {
154
+ return null;
155
+ }
156
+ if (prop.key.type !== "Identifier") {
157
+ return null;
158
+ }
159
+ const keyName = prop.key.name;
160
+ let valueName = null;
161
+ if (prop.value.type === "Identifier") {
162
+ valueName = prop.value.name;
163
+ } else if (prop.value.type === "AssignmentPattern") {
164
+ if (prop.value.left.type === "Identifier") {
165
+ valueName = prop.value.left.name;
166
+ } else {
167
+ return null;
168
+ }
169
+ } else {
170
+ return null;
171
+ }
172
+ if (valueName !== keyName) {
173
+ keys.push(`${keyName}: ${valueName}`);
174
+ } else {
175
+ keys.push(keyName);
176
+ }
177
+ }
178
+ return `{ ${keys.join(", ")} }`;
179
+ }
180
+ function buildWrappedExport(fnName, fnHeader, originalFnSrc, innerArgs, awaitKw, asyncKw, apiFolder, filename) {
181
+ const privateName = `__${fnName}`;
182
+ const spanName = `redwoodjs:api:${apiFolder}:${fnName}`;
183
+ return `export const ${fnName} = ${fnHeader}{
184
+ const ${privateName} = ${originalFnSrc}
185
+ const OTEL_TRACER = OTEL_TRACE.getTracer('redwoodjs')
186
+ const OTEL_RESULT = ${awaitKw}OTEL_TRACER.startActiveSpan(
187
+ '${spanName}',
188
+ ${asyncKw}(span) => {
189
+ span.setAttribute('code.function', '${fnName}')
190
+ span.setAttribute('code.filepath', ${JSON.stringify(filename)})
191
+ try {
192
+ const OTEL_INNER_RESULT = ${awaitKw}${privateName}(${innerArgs})
193
+ span.end()
194
+ return OTEL_INNER_RESULT
195
+ } catch (error) {
196
+ span.recordException(error)
197
+ span.setStatus({
198
+ code: 2,
199
+ message:
200
+ error?.message?.split('\\n')[0] ??
201
+ error?.toString()?.split('\\n')[0],
202
+ })
203
+ span.end()
204
+ throw error
205
+ }
206
+ }
207
+ )
208
+ return OTEL_RESULT
209
+ }`;
210
+ }
211
+ // Annotate the CommonJS export names for ESM import in node:
212
+ 0 && (module.exports = {
213
+ applyOtelWrapping
214
+ });
@@ -0,0 +1,4 @@
1
+ export declare function applyHandlerAlsWrapping(code: string, { projectIsEsm }?: {
2
+ projectIsEsm?: boolean;
3
+ }): string | null;
4
+ //# sourceMappingURL=esbuild-plugin-handler-als-wrapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"esbuild-plugin-handler-als-wrapping.d.ts","sourceRoot":"","sources":["../../../src/build/esbuild-plugin-handler-als-wrapping.ts"],"names":[],"mappings":"AAOA,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,MAAM,EACZ,EAAE,YAAoB,EAAE,GAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAA;CAAO,GACxD,MAAM,GAAG,IAAI,CA0Cf"}
@@ -16,12 +16,12 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var esbuild_plugin_cedar_context_wrapping_exports = {};
20
- __export(esbuild_plugin_cedar_context_wrapping_exports, {
21
- applyContextWrapping: () => applyContextWrapping
19
+ var esbuild_plugin_handler_als_wrapping_exports = {};
20
+ __export(esbuild_plugin_handler_als_wrapping_exports, {
21
+ applyHandlerAlsWrapping: () => applyHandlerAlsWrapping
22
22
  });
23
- module.exports = __toCommonJS(esbuild_plugin_cedar_context_wrapping_exports);
24
- function applyContextWrapping(code, { projectIsEsm = false } = {}) {
23
+ module.exports = __toCommonJS(esbuild_plugin_handler_als_wrapping_exports);
24
+ function applyHandlerAlsWrapping(code, { projectIsEsm = false } = {}) {
25
25
  const handlerRe = /^export\s+(?:const|let|var)\s+handler(?:[^=]|=>)*?=(?![>=])/m;
26
26
  const handlerMatch = handlerRe.exec(code);
27
27
  if (!handlerMatch) {
@@ -30,30 +30,30 @@ function applyContextWrapping(code, { projectIsEsm = false } = {}) {
30
30
  const afterEquals = code.slice(handlerMatch.index + handlerMatch[0].length).trimStart();
31
31
  const isAsync = /^async(?:\s*[\(\*]|\s+function)/.test(afterEquals);
32
32
  const storePath = projectIsEsm ? "@cedarjs/context/dist/store.js" : "@cedarjs/context/dist/store";
33
- const importStatement = `import { getAsyncStoreInstance as __rw_getAsyncStoreInstance } from '${storePath}'
33
+ const importStatement = `import { getAsyncStoreInstance as __cedar_getAsyncStoreInstance } from '${storePath}'
34
34
  `;
35
35
  const handlerStart = handlerMatch.index;
36
36
  const before = code.slice(0, handlerStart);
37
37
  const after = code.slice(handlerStart);
38
- const renamed = after.replace(handlerRe, "const __rw_handler =");
38
+ const renamed = after.replace(handlerRe, "const __cedar_handler =");
39
39
  const wrappedHandler = `
40
- export const handler = ${isAsync ? "async " : ""}(__rw_event, __rw__context) => {
40
+ export const handler = ${isAsync ? "async " : ""}(__cedar_event, __cedar_context) => {
41
41
  // The store will be undefined if no context isolation has been performed yet
42
- const __rw_contextStore = __rw_getAsyncStoreInstance().getStore()
43
- if (__rw_contextStore === undefined) {
44
- return __rw_getAsyncStoreInstance().run(
42
+ const __cedar_contextStore = __cedar_getAsyncStoreInstance().getStore()
43
+ if (__cedar_contextStore === undefined) {
44
+ return __cedar_getAsyncStoreInstance().run(
45
45
  new Map(),
46
- __rw_handler,
47
- __rw_event,
48
- __rw__context
46
+ __cedar_handler,
47
+ __cedar_event,
48
+ __cedar_context
49
49
  )
50
50
  }
51
- return __rw_handler(__rw_event, __rw__context)
51
+ return __cedar_handler(__cedar_event, __cedar_context)
52
52
  }
53
53
  `;
54
54
  return before + importStatement + renamed + wrappedHandler;
55
55
  }
56
56
  // Annotate the CommonJS export names for ESM import in node:
57
57
  0 && (module.exports = {
58
- applyContextWrapping
58
+ applyHandlerAlsWrapping
59
59
  });