@faasjs/core 8.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019-present, Zhu Feng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # @faasjs/core
2
+
3
+ FaasJS core package.
4
+
5
+ [![License: MIT](https://img.shields.io/npm/l/@faasjs/core.svg)](https://github.com/faasjs/faasjs/blob/main/packages/core/LICENSE)
6
+ [![NPM Version](https://img.shields.io/npm/v/@faasjs/core.svg)](https://www.npmjs.com/package/@faasjs/core)
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ npm install @faasjs/core
12
+ ```
13
+
14
+ ## Functions
15
+
16
+ - [defineFunc](functions/defineFunc.md)
17
+
18
+ ## Type Aliases
19
+
20
+ - [DefineFuncData](type-aliases/DefineFuncData.md)
21
+ - [DefineFuncOptions](type-aliases/DefineFuncOptions.md)
package/dist/index.cjs ADDED
@@ -0,0 +1,167 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+
28
+ //#endregion
29
+ let _faasjs_func = require("@faasjs/func");
30
+ let _faasjs_http = require("@faasjs/http");
31
+ let zod = require("zod");
32
+ zod = __toESM(zod);
33
+
34
+ //#region src/index.ts
35
+ function formatPluginModuleName(type) {
36
+ if (type.startsWith("npm:")) return type.slice(4);
37
+ if (type.startsWith("@") || type.startsWith(".") || type.startsWith("/") || type.includes(":")) return type;
38
+ return `@faasjs/${type}`;
39
+ }
40
+ function formatPluginClassName(type) {
41
+ return type.replace(/^@[^/]+\//, "").split(/[^A-Za-z0-9]+/).filter(Boolean).map((item) => item.slice(0, 1).toUpperCase() + item.slice(1)).join("");
42
+ }
43
+ function isPluginConstructor(value) {
44
+ if (typeof value !== "function") return false;
45
+ const prototype = value.prototype;
46
+ if (!prototype || typeof prototype !== "object") return false;
47
+ return typeof prototype.onMount === "function" || typeof prototype.onInvoke === "function";
48
+ }
49
+ function normalizeIssueMessage(message) {
50
+ return message.replace(": expected", ", expected").replace(/>=\s+/g, ">=").replace(/<=\s+/g, "<=");
51
+ }
52
+ function formatZodErrorMessage(error) {
53
+ const lines = ["Invalid params"];
54
+ for (const issue of error.issues) {
55
+ const path = issue.path.length ? issue.path.map((item) => String(item)).join(".") : "<root>";
56
+ lines.push(`${path}: ${normalizeIssueMessage(issue.message)}`);
57
+ }
58
+ return lines.join("\n");
59
+ }
60
+ function findPluginByType(func, type) {
61
+ return func.plugins.find((plugin) => plugin.type === type);
62
+ }
63
+ var CoreFunc = class extends _faasjs_func.Func {
64
+ loadedConfigPlugins = false;
65
+ insertPluginBeforeRunHandler(plugin) {
66
+ const index = this.plugins.findIndex((item) => item.type === "handler" && item.name === "handler");
67
+ if (index === -1) this.plugins.push(plugin);
68
+ else this.plugins.splice(index, 0, plugin);
69
+ }
70
+ async resolvePluginConstructor(moduleName, className, pluginName) {
71
+ let mod;
72
+ try {
73
+ mod = await import(moduleName);
74
+ } catch (error) {
75
+ throw Error(`[defineFunc] Failed to load plugin "${pluginName}" from "${moduleName}": ${error.message}`);
76
+ }
77
+ if (className && isPluginConstructor(mod[className])) return mod[className];
78
+ if (isPluginConstructor(mod.default)) return mod.default;
79
+ throw Error(`[defineFunc] Failed to resolve plugin class "${className}" from "${moduleName}" for plugin "${pluginName}". Supported exports are named class "${className}" or default class export.`);
80
+ }
81
+ async loadPluginsFromConfig(config) {
82
+ const pluginConfigs = config.plugins || Object.create(null);
83
+ for (const [key, rawConfig] of Object.entries(pluginConfigs)) {
84
+ const configValue = rawConfig && typeof rawConfig === "object" ? Object.assign(Object.create(null), rawConfig) : Object.create(null);
85
+ const pluginName = typeof configValue.name === "string" && configValue.name.length ? configValue.name : key;
86
+ if (this.plugins.find((plugin) => plugin.name === pluginName)) continue;
87
+ const pluginType = typeof configValue.type === "string" && configValue.type || typeof rawConfig === "string" && rawConfig || key;
88
+ const moduleName = formatPluginModuleName(pluginType);
89
+ const className = formatPluginClassName(pluginType);
90
+ const PluginConstructor = await this.resolvePluginConstructor(moduleName, className, pluginName);
91
+ let plugin;
92
+ try {
93
+ plugin = new PluginConstructor({
94
+ ...configValue,
95
+ name: pluginName,
96
+ type: pluginType
97
+ });
98
+ } catch (error) {
99
+ throw Error(`[defineFunc] Failed to initialize plugin "${pluginName}" from "${moduleName}": ${error.message}`);
100
+ }
101
+ if (!plugin || typeof plugin !== "object") throw Error(`[defineFunc] Invalid plugin instance for "${pluginName}" from "${moduleName}".`);
102
+ this.insertPluginBeforeRunHandler(plugin);
103
+ }
104
+ this.loadedConfigPlugins = true;
105
+ }
106
+ async mount(data = {
107
+ event: Object.create(null),
108
+ context: Object.create(null)
109
+ }) {
110
+ if (!data.config) data.config = this.config;
111
+ if (!this.loadedConfigPlugins) await this.loadPluginsFromConfig(data.config);
112
+ await super.mount(data);
113
+ }
114
+ };
115
+ /**
116
+ * Create a cloud function with optional Zod validation.
117
+ *
118
+ * Plugins are always auto-loaded from `func.config.plugins`.
119
+ * Plugin module exports must be either a named class (normalized from
120
+ * plugin type) or a default class export.
121
+ */
122
+ function defineFunc(options) {
123
+ let func;
124
+ let pluginRefsResolved = false;
125
+ let hasHttp = false;
126
+ let knexQuery;
127
+ const resolvePluginRefs = () => {
128
+ if (pluginRefsResolved) return;
129
+ hasHttp = !!findPluginByType(func, "http");
130
+ knexQuery = findPluginByType(func, "knex")?.query;
131
+ pluginRefsResolved = true;
132
+ };
133
+ const parseParams = async (event) => {
134
+ if (!hasHttp) return void 0;
135
+ if (!options.schema) return {};
136
+ const result = await options.schema.safeParseAsync(event?.params ?? {});
137
+ if (!result.success) throw new _faasjs_http.HttpError({
138
+ statusCode: 400,
139
+ message: formatZodErrorMessage(result.error)
140
+ });
141
+ return result.data;
142
+ };
143
+ const invokeHandler = async (data) => {
144
+ resolvePluginRefs();
145
+ const params = await parseParams(data.event);
146
+ const invokeData = {
147
+ ...data,
148
+ params,
149
+ knex: knexQuery
150
+ };
151
+ return options.handler(invokeData);
152
+ };
153
+ func = new CoreFunc({
154
+ plugins: [],
155
+ handler: invokeHandler
156
+ });
157
+ return func;
158
+ }
159
+
160
+ //#endregion
161
+ exports.defineFunc = defineFunc;
162
+ Object.defineProperty(exports, 'z', {
163
+ enumerable: true,
164
+ get: function () {
165
+ return zod;
166
+ }
167
+ });
@@ -0,0 +1,26 @@
1
+ import { Func, InvokeData } from "@faasjs/func";
2
+ import { Knex } from "@faasjs/knex";
3
+ import * as z from "zod";
4
+ import { ZodTypeAny, output } from "zod";
5
+
6
+ //#region src/index.d.ts
7
+ type ZodSchema = ZodTypeAny;
8
+ type KnexQuery = Knex['query'];
9
+ type DefineFuncData<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any> = InvokeData<TEvent, TContext, TResult> & {
10
+ params: (TSchema extends ZodSchema ? output<NonNullable<TSchema>> : Record<string, never>) | undefined;
11
+ knex: KnexQuery | undefined;
12
+ };
13
+ type DefineFuncOptions<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any> = {
14
+ schema?: TSchema;
15
+ handler: (data: DefineFuncData<TSchema, TEvent, TContext, TResult>) => Promise<TResult>;
16
+ };
17
+ /**
18
+ * Create a cloud function with optional Zod validation.
19
+ *
20
+ * Plugins are always auto-loaded from `func.config.plugins`.
21
+ * Plugin module exports must be either a named class (normalized from
22
+ * plugin type) or a default class export.
23
+ */
24
+ declare function defineFunc<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any>(options: DefineFuncOptions<TSchema, TEvent, TContext, TResult>): Func<TEvent, TContext, TResult>;
25
+ //#endregion
26
+ export { DefineFuncData, DefineFuncOptions, defineFunc, z };
package/dist/index.mjs ADDED
@@ -0,0 +1,132 @@
1
+ import { Func } from "@faasjs/func";
2
+ import { HttpError } from "@faasjs/http";
3
+ import * as z from "zod";
4
+
5
+ //#region src/index.ts
6
+ function formatPluginModuleName(type) {
7
+ if (type.startsWith("npm:")) return type.slice(4);
8
+ if (type.startsWith("@") || type.startsWith(".") || type.startsWith("/") || type.includes(":")) return type;
9
+ return `@faasjs/${type}`;
10
+ }
11
+ function formatPluginClassName(type) {
12
+ return type.replace(/^@[^/]+\//, "").split(/[^A-Za-z0-9]+/).filter(Boolean).map((item) => item.slice(0, 1).toUpperCase() + item.slice(1)).join("");
13
+ }
14
+ function isPluginConstructor(value) {
15
+ if (typeof value !== "function") return false;
16
+ const prototype = value.prototype;
17
+ if (!prototype || typeof prototype !== "object") return false;
18
+ return typeof prototype.onMount === "function" || typeof prototype.onInvoke === "function";
19
+ }
20
+ function normalizeIssueMessage(message) {
21
+ return message.replace(": expected", ", expected").replace(/>=\s+/g, ">=").replace(/<=\s+/g, "<=");
22
+ }
23
+ function formatZodErrorMessage(error) {
24
+ const lines = ["Invalid params"];
25
+ for (const issue of error.issues) {
26
+ const path = issue.path.length ? issue.path.map((item) => String(item)).join(".") : "<root>";
27
+ lines.push(`${path}: ${normalizeIssueMessage(issue.message)}`);
28
+ }
29
+ return lines.join("\n");
30
+ }
31
+ function findPluginByType(func, type) {
32
+ return func.plugins.find((plugin) => plugin.type === type);
33
+ }
34
+ var CoreFunc = class extends Func {
35
+ loadedConfigPlugins = false;
36
+ insertPluginBeforeRunHandler(plugin) {
37
+ const index = this.plugins.findIndex((item) => item.type === "handler" && item.name === "handler");
38
+ if (index === -1) this.plugins.push(plugin);
39
+ else this.plugins.splice(index, 0, plugin);
40
+ }
41
+ async resolvePluginConstructor(moduleName, className, pluginName) {
42
+ let mod;
43
+ try {
44
+ mod = await import(moduleName);
45
+ } catch (error) {
46
+ throw Error(`[defineFunc] Failed to load plugin "${pluginName}" from "${moduleName}": ${error.message}`);
47
+ }
48
+ if (className && isPluginConstructor(mod[className])) return mod[className];
49
+ if (isPluginConstructor(mod.default)) return mod.default;
50
+ throw Error(`[defineFunc] Failed to resolve plugin class "${className}" from "${moduleName}" for plugin "${pluginName}". Supported exports are named class "${className}" or default class export.`);
51
+ }
52
+ async loadPluginsFromConfig(config) {
53
+ const pluginConfigs = config.plugins || Object.create(null);
54
+ for (const [key, rawConfig] of Object.entries(pluginConfigs)) {
55
+ const configValue = rawConfig && typeof rawConfig === "object" ? Object.assign(Object.create(null), rawConfig) : Object.create(null);
56
+ const pluginName = typeof configValue.name === "string" && configValue.name.length ? configValue.name : key;
57
+ if (this.plugins.find((plugin) => plugin.name === pluginName)) continue;
58
+ const pluginType = typeof configValue.type === "string" && configValue.type || typeof rawConfig === "string" && rawConfig || key;
59
+ const moduleName = formatPluginModuleName(pluginType);
60
+ const className = formatPluginClassName(pluginType);
61
+ const PluginConstructor = await this.resolvePluginConstructor(moduleName, className, pluginName);
62
+ let plugin;
63
+ try {
64
+ plugin = new PluginConstructor({
65
+ ...configValue,
66
+ name: pluginName,
67
+ type: pluginType
68
+ });
69
+ } catch (error) {
70
+ throw Error(`[defineFunc] Failed to initialize plugin "${pluginName}" from "${moduleName}": ${error.message}`);
71
+ }
72
+ if (!plugin || typeof plugin !== "object") throw Error(`[defineFunc] Invalid plugin instance for "${pluginName}" from "${moduleName}".`);
73
+ this.insertPluginBeforeRunHandler(plugin);
74
+ }
75
+ this.loadedConfigPlugins = true;
76
+ }
77
+ async mount(data = {
78
+ event: Object.create(null),
79
+ context: Object.create(null)
80
+ }) {
81
+ if (!data.config) data.config = this.config;
82
+ if (!this.loadedConfigPlugins) await this.loadPluginsFromConfig(data.config);
83
+ await super.mount(data);
84
+ }
85
+ };
86
+ /**
87
+ * Create a cloud function with optional Zod validation.
88
+ *
89
+ * Plugins are always auto-loaded from `func.config.plugins`.
90
+ * Plugin module exports must be either a named class (normalized from
91
+ * plugin type) or a default class export.
92
+ */
93
+ function defineFunc(options) {
94
+ let func;
95
+ let pluginRefsResolved = false;
96
+ let hasHttp = false;
97
+ let knexQuery;
98
+ const resolvePluginRefs = () => {
99
+ if (pluginRefsResolved) return;
100
+ hasHttp = !!findPluginByType(func, "http");
101
+ knexQuery = findPluginByType(func, "knex")?.query;
102
+ pluginRefsResolved = true;
103
+ };
104
+ const parseParams = async (event) => {
105
+ if (!hasHttp) return void 0;
106
+ if (!options.schema) return {};
107
+ const result = await options.schema.safeParseAsync(event?.params ?? {});
108
+ if (!result.success) throw new HttpError({
109
+ statusCode: 400,
110
+ message: formatZodErrorMessage(result.error)
111
+ });
112
+ return result.data;
113
+ };
114
+ const invokeHandler = async (data) => {
115
+ resolvePluginRefs();
116
+ const params = await parseParams(data.event);
117
+ const invokeData = {
118
+ ...data,
119
+ params,
120
+ knex: knexQuery
121
+ };
122
+ return options.handler(invokeData);
123
+ };
124
+ func = new CoreFunc({
125
+ plugins: [],
126
+ handler: invokeHandler
127
+ });
128
+ return func;
129
+ }
130
+
131
+ //#endregion
132
+ export { defineFunc, z };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@faasjs/core",
3
+ "version": "8.0.0-beta.7",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "homepage": "https://faasjs.com/doc/core",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/faasjs/faasjs.git",
20
+ "directory": "packages/core"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/faasjs/faasjs/issues"
24
+ },
25
+ "funding": "https://github.com/sponsors/faasjs",
26
+ "scripts": {
27
+ "build": "tsdown src/index.ts --config ../../tsdown.config.ts"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "peerDependencies": {
33
+ "@faasjs/types": ">=8.0.0-beta.7",
34
+ "@faasjs/func": ">=8.0.0-beta.7",
35
+ "@faasjs/http": ">=8.0.0-beta.7",
36
+ "@faasjs/knex": ">=8.0.0-beta.7",
37
+ "zod": ">=4.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@faasjs/types": ">=8.0.0-beta.7",
41
+ "@faasjs/func": ">=8.0.0-beta.7",
42
+ "@faasjs/http": ">=8.0.0-beta.7",
43
+ "@faasjs/knex": ">=8.0.0-beta.7",
44
+ "zod": ">=4.0.0"
45
+ },
46
+ "engines": {
47
+ "node": ">=24.0.0",
48
+ "npm": ">=11.0.0"
49
+ }
50
+ }