@molecule/api-resource 1.0.0

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 (58) hide show
  1. package/LICENSE +115 -0
  2. package/dist/browser-guard.d.ts +2 -0
  3. package/dist/browser-guard.d.ts.map +1 -0
  4. package/dist/browser-guard.js +19 -0
  5. package/dist/browser-guard.js.map +1 -0
  6. package/dist/create.d.ts +58 -0
  7. package/dist/create.d.ts.map +1 -0
  8. package/dist/create.js +87 -0
  9. package/dist/create.js.map +1 -0
  10. package/dist/createRequestHandler.d.ts +48 -0
  11. package/dist/createRequestHandler.d.ts.map +1 -0
  12. package/dist/createRequestHandler.js +42 -0
  13. package/dist/createRequestHandler.js.map +1 -0
  14. package/dist/del.d.ts +55 -0
  15. package/dist/del.d.ts.map +1 -0
  16. package/dist/del.js +63 -0
  17. package/dist/del.js.map +1 -0
  18. package/dist/http-types.d.ts +58 -0
  19. package/dist/http-types.d.ts.map +1 -0
  20. package/dist/http-types.js +11 -0
  21. package/dist/http-types.js.map +1 -0
  22. package/dist/i18n.d.ts +11 -0
  23. package/dist/i18n.d.ts.map +1 -0
  24. package/dist/i18n.js +19 -0
  25. package/dist/i18n.js.map +1 -0
  26. package/dist/index.d.ts +100 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +100 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/query.d.ts +102 -0
  31. package/dist/query.d.ts.map +1 -0
  32. package/dist/query.js +100 -0
  33. package/dist/query.js.map +1 -0
  34. package/dist/read.d.ts +57 -0
  35. package/dist/read.d.ts.map +1 -0
  36. package/dist/read.js +56 -0
  37. package/dist/read.js.map +1 -0
  38. package/dist/respond-error.d.ts +44 -0
  39. package/dist/respond-error.d.ts.map +1 -0
  40. package/dist/respond-error.js +46 -0
  41. package/dist/respond-error.js.map +1 -0
  42. package/dist/schema.d.ts +81 -0
  43. package/dist/schema.d.ts.map +1 -0
  44. package/dist/schema.js +112 -0
  45. package/dist/schema.js.map +1 -0
  46. package/dist/types.d.ts +88 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +10 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/update.d.ts +59 -0
  51. package/dist/update.d.ts.map +1 -0
  52. package/dist/update.js +82 -0
  53. package/dist/update.js.map +1 -0
  54. package/dist/utilities/index.d.ts +9 -0
  55. package/dist/utilities/index.d.ts.map +1 -0
  56. package/dist/utilities/index.js +9 -0
  57. package/dist/utilities/index.js.map +1 -0
  58. package/package.json +66 -0
package/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-resource` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-resource is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
19
+ //# sourceMappingURL=browser-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.js","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,GAAG,UAIT,CAAA;AACD,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IACrF,MAAM,IAAI,KAAK,CACb,iGAAiG;QAC/F,sFAAsF;QACtF,iFAAiF;QACjF,0CAA0C,CAC7C,CAAA;AACH,CAAC"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Resource create operation.
3
+ *
4
+ * @module
5
+ */
6
+ import type * as types from './types.js';
7
+ /**
8
+ * Creates a handler to create a resource.
9
+ *
10
+ * Uses the bonded DataStore from `@molecule/api-database` for database-agnostic operations.
11
+ *
12
+ * Example usage:
13
+ * ```ts
14
+ * import { create as resourceCreate } from '@molecule/api-resource'
15
+ * import type * as types from '../../types.js'
16
+ *
17
+ * export const create = ({ name, tableName, schema }: types.Resource) => {
18
+ * const create = resourceCreate({ name, tableName, schema })
19
+ *
20
+ * return async (req: MoleculeRequest) => {
21
+ * const props = req.body
22
+ * return await create({ props })
23
+ * }
24
+ * }
25
+ * ```
26
+ * @param resource - The resource descriptor.
27
+ * @param resource.name - Human-readable resource name used in error messages (e.g. `'User'`).
28
+ * @param resource.tableName - Database table to insert the new row into.
29
+ * @param resource.schema - Zod schema to validate the incoming props against.
30
+ * @returns A curried async function that accepts `{ props, id? }` and returns a `{ statusCode, body }` response.
31
+ */
32
+ export declare const create: <CreateProps extends Record<string, unknown> = Record<string, unknown>, CreatedProps extends types.Props & CreateProps = types.Props & CreateProps>({ name, tableName, schema, }: types.Resource) => ({ props: createProps, id, }: {
33
+ /**
34
+ * The properties of the resource to be created.
35
+ *
36
+ * Usually from `req.body`.
37
+ */
38
+ props: CreateProps;
39
+ /**
40
+ * Defaults a new UUID when not provided.
41
+ */
42
+ id?: CreatedProps["id"];
43
+ }) => Promise<{
44
+ statusCode: number;
45
+ body: {
46
+ error: string;
47
+ errorKey: string;
48
+ props?: undefined;
49
+ };
50
+ } | {
51
+ statusCode: number;
52
+ body: {
53
+ props: CreatedProps;
54
+ error?: undefined;
55
+ errorKey?: undefined;
56
+ };
57
+ }>;
58
+ //# sourceMappingURL=create.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAUH,OAAO,KAAK,KAAK,KAAK,MAAM,YAAY,CAAA;AAGxC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,MAAM,GAEf,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrE,YAAY,SAAS,KAAK,CAAC,KAAK,GAAG,WAAW,GAAG,KAAK,CAAC,KAAK,GAAG,WAAW,EAC1E,8BAIC,KAAK,CAAC,QAAQ,MACV,6BAGJ;IACD;;;;OAIG;IACH,KAAK,EAAE,WAAW,CAAA;IAClB;;OAEG;IACH,EAAE,CAAC,EAAE,YAAY,CAAC,IAAI,CAAC,CAAA;CACxB;;;;;;;;;;;;;;EAyDA,CAAA"}
package/dist/create.js ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Resource create operation.
3
+ *
4
+ * @module
5
+ */
6
+ import { v4 as uuid } from 'uuid';
7
+ import { getLogger } from '@molecule/api-bond';
8
+ const logger = getLogger();
9
+ import { create as storeCreate } from '@molecule/api-database';
10
+ import { t } from '@molecule/api-i18n';
11
+ import { getValidProps } from './utilities/index.js';
12
+ /**
13
+ * Creates a handler to create a resource.
14
+ *
15
+ * Uses the bonded DataStore from `@molecule/api-database` for database-agnostic operations.
16
+ *
17
+ * Example usage:
18
+ * ```ts
19
+ * import { create as resourceCreate } from '@molecule/api-resource'
20
+ * import type * as types from '../../types.js'
21
+ *
22
+ * export const create = ({ name, tableName, schema }: types.Resource) => {
23
+ * const create = resourceCreate({ name, tableName, schema })
24
+ *
25
+ * return async (req: MoleculeRequest) => {
26
+ * const props = req.body
27
+ * return await create({ props })
28
+ * }
29
+ * }
30
+ * ```
31
+ * @param resource - The resource descriptor.
32
+ * @param resource.name - Human-readable resource name used in error messages (e.g. `'User'`).
33
+ * @param resource.tableName - Database table to insert the new row into.
34
+ * @param resource.schema - Zod schema to validate the incoming props against.
35
+ * @returns A curried async function that accepts `{ props, id? }` and returns a `{ statusCode, body }` response.
36
+ */
37
+ export const create = ({ name, tableName, schema, }) => async ({ props: createProps, id, }) => {
38
+ // TypeScript 5+ requires explicit unknown cast for generic type conversions
39
+ let props = createProps;
40
+ try {
41
+ // Assign an `id` to this types.
42
+ id = id || uuid();
43
+ props.id = id;
44
+ // Always set server-controlled timestamps — never trust client-supplied values.
45
+ const now = new Date().toISOString();
46
+ props.createdAt = now;
47
+ props.updatedAt = now;
48
+ // Validate the new resource's `props`.
49
+ props = getValidProps({
50
+ name,
51
+ schema: schema,
52
+ props,
53
+ });
54
+ }
55
+ catch (error) {
56
+ // The provided `props` failed validation.
57
+ return {
58
+ statusCode: 400,
59
+ body: {
60
+ error: error
61
+ ? String(error)
62
+ : t('resource.error.unknownError', undefined, { defaultValue: 'Unknown error.' }),
63
+ errorKey: 'resource.error.unknownError',
64
+ },
65
+ };
66
+ }
67
+ try {
68
+ // Insert the new resource into the database via the bonded DataStore.
69
+ const result = await storeCreate(tableName, props);
70
+ if (!result.affected) {
71
+ throw new Error(`Failed to insert data into ${tableName}.`);
72
+ }
73
+ // If we made it here, the data was successfully inserted into the database.
74
+ return { statusCode: 201, body: { props } };
75
+ }
76
+ catch (error) {
77
+ logger.error(error);
78
+ return {
79
+ statusCode: error.statusCode || 400,
80
+ body: {
81
+ error: t('resource.error.unableToCreate', { name }, { defaultValue: `Unable to create ${name}.` }),
82
+ errorKey: 'resource.error.unableToCreate',
83
+ },
84
+ };
85
+ }
86
+ };
87
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAA;AAGjC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,MAAM,MAAM,GAAG,SAAS,EAAE,CAAA;AAC1B,OAAO,EAAE,MAAM,IAAI,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAC9D,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAGtC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,MAAM,MAAM,GACjB,CAGE,EACA,IAAI,EACJ,SAAS,EACT,MAAM,GACS,EAAE,EAAE,CACrB,KAAK,EAAE,EACL,KAAK,EAAE,WAAW,EAClB,EAAE,GAYH,EAAE,EAAE;IACH,4EAA4E;IAC5E,IAAI,KAAK,GAAG,WAAsC,CAAA;IAElD,IAAI,CAAC;QACH,gCAAgC;QAChC,EAAE,GAAG,EAAE,IAAI,IAAI,EAAE,CAAA;QACjB,KAAK,CAAC,EAAE,GAAG,EAAE,CAAA;QAEb,gFAAgF;QAChF,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAA;QACpC,KAAK,CAAC,SAAS,GAAG,GAAG,CAAA;QACrB,KAAK,CAAC,SAAS,GAAG,GAAG,CAAA;QAErB,uCAAuC;QACvC,KAAK,GAAG,aAAa,CAAe;YAClC,IAAI;YACJ,MAAM,EAAE,MAA4C;YACpD,KAAK;SACN,CAAC,CAAA;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,0CAA0C;QAC1C,OAAO;YACL,UAAU,EAAE,GAAG;YACf,IAAI,EAAE;gBACJ,KAAK,EAAE,KAAK;oBACV,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;oBACf,CAAC,CAAC,CAAC,CAAC,6BAA6B,EAAE,SAAS,EAAE,EAAE,YAAY,EAAE,gBAAgB,EAAE,CAAC;gBACnF,QAAQ,EAAE,6BAA6B;aACxC;SACF,CAAA;IACH,CAAC;IAED,IAAI,CAAC;QACH,sEAAsE;QACtE,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,SAAS,EAAE,KAA2C,CAAC,CAAA;QAExF,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,8BAA8B,SAAS,GAAG,CAAC,CAAA;QAC7D,CAAC;QAED,4EAA4E;QAC5E,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,CAAA;IAC7C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACnB,OAAO;YACL,UAAU,EAAG,KAAiC,CAAC,UAAU,IAAI,GAAG;YAChE,IAAI,EAAE;gBACJ,KAAK,EAAE,CAAC,CACN,+BAA+B,EAC/B,EAAE,IAAI,EAAE,EACR,EAAE,YAAY,EAAE,oBAAoB,IAAI,GAAG,EAAE,CAC9C;gBACD,QAAQ,EAAE,+BAA+B;aAC1C;SACF,CAAA;IACH,CAAC;AACH,CAAC,CAAA"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Wraps resource handler functions into Express-compatible middleware.
3
+ *
4
+ * Resource handlers return `{ statusCode, headers?, body }` objects instead of
5
+ * calling `res.status().send()` directly, making them easier to test and
6
+ * reuse across different HTTP frameworks (Express, Lambda, etc.).
7
+ *
8
+ * @module
9
+ */
10
+ import type { MoleculeNextFunction, MoleculeRequest, MoleculeResponse } from './http-types.js';
11
+ /**
12
+ * A resource handler function that processes a request and returns a structured
13
+ * response object. If it returns `null` or `undefined`, the request is passed
14
+ * to the next middleware via `next()`.
15
+ *
16
+ * @param req - The incoming HTTP request.
17
+ * @param res - The HTTP response (available but handlers should return a Response instead of calling `res` directly).
18
+ */
19
+ export type Handler = (req: MoleculeRequest, res: MoleculeResponse) => Promise<Response | null | undefined> | Response | null | undefined;
20
+ /**
21
+ * Structured response object returned by resource handlers. Contains the HTTP
22
+ * status code, optional headers, and the response body payload.
23
+ */
24
+ export interface Response {
25
+ /**
26
+ * HTTP status code to return.
27
+ */
28
+ statusCode: number;
29
+ /**
30
+ * Optional map of HTTP header keys to values.
31
+ */
32
+ headers?: Record<string, string>;
33
+ /**
34
+ * The response payload to return.
35
+ */
36
+ body: any;
37
+ }
38
+ /**
39
+ * Wraps a resource handler into Express-compatible middleware. Calls the handler,
40
+ * then applies `statusCode`, `headers`, and `body` to the response. If the handler
41
+ * returns null/undefined, calls `next()`. Catches errors and forwards them as
42
+ * i18n-translated error messages.
43
+ *
44
+ * @param handler - The resource handler function to wrap.
45
+ * @returns An Express-compatible middleware function `(req, res, next) => void`.
46
+ */
47
+ export declare const createRequestHandler: (handler: Handler) => (req: MoleculeRequest, res: MoleculeResponse, next: MoleculeNextFunction) => Promise<void>;
48
+ //# sourceMappingURL=createRequestHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createRequestHandler.d.ts","sourceRoot":"","sources":["../src/createRequestHandler.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EAAE,oBAAoB,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAI9F;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,gBAAgB,KAClB,OAAO,CAAC,QAAQ,GAAG,IAAI,GAAG,SAAS,CAAC,GAAG,QAAQ,GAAG,IAAI,GAAG,SAAS,CAAA;AAEvE;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACvB;;OAEG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC;;OAEG;IACH,IAAI,EAAE,GAAG,CAAA;CACV;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,oBAAoB,GAC9B,SAAS,OAAO,MACV,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,oBAAoB,kBAkB7E,CAAA"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Wraps resource handler functions into Express-compatible middleware.
3
+ *
4
+ * Resource handlers return `{ statusCode, headers?, body }` objects instead of
5
+ * calling `res.status().send()` directly, making them easier to test and
6
+ * reuse across different HTTP frameworks (Express, Lambda, etc.).
7
+ *
8
+ * @module
9
+ */
10
+ /* eslint-disable @typescript-eslint/no-explicit-any */
11
+ import { getLogger } from '@molecule/api-bond';
12
+ const logger = getLogger();
13
+ import { t } from '@molecule/api-i18n';
14
+ /**
15
+ * Wraps a resource handler into Express-compatible middleware. Calls the handler,
16
+ * then applies `statusCode`, `headers`, and `body` to the response. If the handler
17
+ * returns null/undefined, calls `next()`. Catches errors and forwards them as
18
+ * i18n-translated error messages.
19
+ *
20
+ * @param handler - The resource handler function to wrap.
21
+ * @returns An Express-compatible middleware function `(req, res, next) => void`.
22
+ */
23
+ export const createRequestHandler = (handler) => async (req, res, next) => {
24
+ try {
25
+ const response = await handler(req, res);
26
+ if (response) {
27
+ if (response.headers) {
28
+ res.set(response.headers);
29
+ }
30
+ res.status(response.statusCode);
31
+ res.send(response.body);
32
+ }
33
+ else {
34
+ next();
35
+ }
36
+ }
37
+ catch (error) {
38
+ logger.error(error);
39
+ next(t('resource.error.unknownError', undefined, { defaultValue: 'Something went wrong.' }));
40
+ }
41
+ };
42
+ //# sourceMappingURL=createRequestHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createRequestHandler.js","sourceRoot":"","sources":["../src/createRequestHandler.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,uDAAuD;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAG9C,MAAM,MAAM,GAAG,SAAS,EAAE,CAAA;AAC1B,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAkCtC;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAC/B,CAAC,OAAgB,EAAE,EAAE,CACrB,KAAK,EAAE,GAAoB,EAAE,GAAqB,EAAE,IAA0B,EAAE,EAAE;IAChF,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;QAExC,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,QAAQ,CAAC,OAAO,EAAE,CAAC;gBACrB,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;YAC3B,CAAC;YAED,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAA;YAC/B,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;QACzB,CAAC;aAAM,CAAC;YACN,IAAI,EAAE,CAAA;QACR,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACnB,IAAI,CAAC,CAAC,CAAC,6BAA6B,EAAE,SAAS,EAAE,EAAE,YAAY,EAAE,uBAAuB,EAAE,CAAC,CAAC,CAAA;IAC9F,CAAC;AACH,CAAC,CAAA"}
package/dist/del.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Resource delete operation.
3
+ *
4
+ * @module
5
+ */
6
+ import type * as types from './types.js';
7
+ /**
8
+ * Creates a handler to delete a resource by its `id`.
9
+ *
10
+ * > **Note:** We use `del` everywhere instead of `delete` since `delete` is a reserved keyword in JavaScript.
11
+ *
12
+ * Uses the bonded DataStore from `@molecule/api-database` for database-agnostic operations.
13
+ *
14
+ * Example usage:
15
+ * ```ts
16
+ * import { del as resourceDel } from '@molecule/api-resource'
17
+ * import type * as types from '../../types.js'
18
+ *
19
+ * export const del = ({ name, tableName, schema }: types.Resource) => {
20
+ * const del = resourceDel({ name, tableName, schema })
21
+ *
22
+ * return async (req: MoleculeRequest) => {
23
+ * const id = req.params.id
24
+ * return await del({ id })
25
+ * }
26
+ * }
27
+ * ```
28
+ * @param resource - The resource descriptor.
29
+ * @param resource.name - Human-readable resource name used in error messages (e.g. `'User'`).
30
+ * @param resource.tableName - Database table to delete the row from.
31
+ * @returns A curried async function that accepts `{ id }` and returns a `{ statusCode, body }` response.
32
+ */
33
+ export declare const del: <Props extends types.Props = types.Props, DeletedResource extends types.Resource<Props> = types.Resource<Props>>({ name, tableName, }: DeletedResource) => ({ id, }: {
34
+ /**
35
+ * The `id` of the resource to be deleted.
36
+ */
37
+ id: Props["id"];
38
+ }) => Promise<{
39
+ statusCode: number;
40
+ body: {
41
+ error: string;
42
+ errorKey: string;
43
+ props?: undefined;
44
+ };
45
+ } | {
46
+ statusCode: number;
47
+ body: {
48
+ props: {
49
+ id: Props["id"];
50
+ };
51
+ error?: undefined;
52
+ errorKey?: undefined;
53
+ };
54
+ }>;
55
+ //# sourceMappingURL=del.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"del.d.ts","sourceRoot":"","sources":["../src/del.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAOH,OAAO,KAAK,KAAK,KAAK,MAAM,YAAY,CAAA;AAExC;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,GAAG,GAEZ,KAAK,SAAS,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,EACvC,eAAe,SAAS,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EACrE,sBAGC,eAAe,MACX,SAEJ;IACD;;OAEG;IACH,EAAE,EAAE,KAAK,CAAC,IAAI,CAAC,CAAA;CAChB;;;;;;;;;;;;;;;;EA+BA,CAAA"}
package/dist/del.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Resource delete operation.
3
+ *
4
+ * @module
5
+ */
6
+ import { getLogger } from '@molecule/api-bond';
7
+ const logger = getLogger();
8
+ import { deleteById } from '@molecule/api-database';
9
+ import { t } from '@molecule/api-i18n';
10
+ /**
11
+ * Creates a handler to delete a resource by its `id`.
12
+ *
13
+ * > **Note:** We use `del` everywhere instead of `delete` since `delete` is a reserved keyword in JavaScript.
14
+ *
15
+ * Uses the bonded DataStore from `@molecule/api-database` for database-agnostic operations.
16
+ *
17
+ * Example usage:
18
+ * ```ts
19
+ * import { del as resourceDel } from '@molecule/api-resource'
20
+ * import type * as types from '../../types.js'
21
+ *
22
+ * export const del = ({ name, tableName, schema }: types.Resource) => {
23
+ * const del = resourceDel({ name, tableName, schema })
24
+ *
25
+ * return async (req: MoleculeRequest) => {
26
+ * const id = req.params.id
27
+ * return await del({ id })
28
+ * }
29
+ * }
30
+ * ```
31
+ * @param resource - The resource descriptor.
32
+ * @param resource.name - Human-readable resource name used in error messages (e.g. `'User'`).
33
+ * @param resource.tableName - Database table to delete the row from.
34
+ * @returns A curried async function that accepts `{ id }` and returns a `{ statusCode, body }` response.
35
+ */
36
+ export const del = ({ name, tableName, }) => async ({ id, }) => {
37
+ try {
38
+ // Delete the resource from the database via the bonded DataStore.
39
+ const result = await deleteById(tableName, id);
40
+ if (!result || !result.affected) {
41
+ return {
42
+ statusCode: 404,
43
+ body: {
44
+ error: t('resource.error.notFound', undefined, { defaultValue: 'Not found.' }),
45
+ errorKey: 'resource.error.notFound',
46
+ },
47
+ };
48
+ }
49
+ // If we made it here, updates to the database were successful.
50
+ return { statusCode: 200, body: { props: { id } } };
51
+ }
52
+ catch (error) {
53
+ logger.error(error);
54
+ return {
55
+ statusCode: error.statusCode || 400,
56
+ body: {
57
+ error: t('resource.error.unableToDelete', { name }, { defaultValue: `Unable to delete ${name}.` }),
58
+ errorKey: 'resource.error.unableToDelete',
59
+ },
60
+ };
61
+ }
62
+ };
63
+ //# sourceMappingURL=del.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"del.js","sourceRoot":"","sources":["../src/del.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,MAAM,MAAM,GAAG,SAAS,EAAE,CAAA;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAItC;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,MAAM,GAAG,GACd,CAGE,EACA,IAAI,EACJ,SAAS,GACO,EAAE,EAAE,CACtB,KAAK,EAAE,EACL,EAAE,GAMH,EAAE,EAAE;IACH,IAAI,CAAC;QACH,kEAAkE;QAClE,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;QAE9C,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YAChC,OAAO;gBACL,UAAU,EAAE,GAAG;gBACf,IAAI,EAAE;oBACJ,KAAK,EAAE,CAAC,CAAC,yBAAyB,EAAE,SAAS,EAAE,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC;oBAC9E,QAAQ,EAAE,yBAAyB;iBACpC;aACF,CAAA;QACH,CAAC;QAED,+DAA+D;QAC/D,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAA;IACrD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACnB,OAAO;YACL,UAAU,EAAG,KAAiC,CAAC,UAAU,IAAI,GAAG;YAChE,IAAI,EAAE;gBACJ,KAAK,EAAE,CAAC,CACN,+BAA+B,EAC/B,EAAE,IAAI,EAAE,EACR,EAAE,YAAY,EAAE,oBAAoB,IAAI,GAAG,EAAE,CAC9C;gBACD,QAAQ,EAAE,+BAA+B;aAC1C;SACF,CAAA;IACH,CAAC;AACH,CAAC,CAAA"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Framework-agnostic HTTP types for molecule.dev resource handlers.
3
+ *
4
+ * These are structural subtypes of Express types — Express objects satisfy them
5
+ * without adapters. Allows resource handlers to be used with any HTTP framework
6
+ * (Express, Fastify, Hono, etc.) by depending on these interfaces instead of Express directly.
7
+ *
8
+ * @module
9
+ */
10
+ /**
11
+ * Framework-agnostic HTTP request interface. Structurally compatible with Express's
12
+ * `Request` — Express objects satisfy this interface without adapters, but the type
13
+ * doesn't depend on Express, allowing use with Fastify, Hono, or Lambda.
14
+ */
15
+ export interface MoleculeRequest {
16
+ body: any;
17
+ params: Record<string, string>;
18
+ query: Record<string, any>;
19
+ headers: Record<string, string | string[] | undefined>;
20
+ cookies?: Record<string, string>;
21
+ /**
22
+ * Client IP address. Populated by Express (honoring `trust proxy`) and other
23
+ * frameworks; optional because it isn't guaranteed in every adapter. Used for
24
+ * IP-keyed rate limiting on auth endpoints.
25
+ */
26
+ ip?: string;
27
+ on?(event: string, listener: (...args: unknown[]) => void): void;
28
+ }
29
+ /**
30
+ * Framework-agnostic HTTP response interface. Structurally compatible with Express's
31
+ * `Response` — includes `status()`, `json()`, `send()`, `set()`, cookie methods,
32
+ * streaming (`write`), and `locals` for per-request data sharing.
33
+ */
34
+ export interface MoleculeResponse {
35
+ status(code: number): this;
36
+ json(body: unknown): void;
37
+ send(body: unknown): void;
38
+ end(): void;
39
+ set(headers: Record<string, string>): void;
40
+ setHeader(name: string, value: string): void;
41
+ cookie(name: string, value: string, options?: Record<string, unknown>): void;
42
+ write(chunk: string | Buffer): boolean;
43
+ flushHeaders?(): void;
44
+ locals: Record<string, any>;
45
+ }
46
+ /**
47
+ * Framework-agnostic next function. Call with no arguments to pass to the next
48
+ * middleware, or with an error to trigger error-handling middleware.
49
+ *
50
+ * @param err - Optional error to forward to error-handling middleware.
51
+ */
52
+ export type MoleculeNextFunction = (err?: unknown) => void;
53
+ /**
54
+ * Framework-agnostic middleware function signature matching Express's
55
+ * `(req, res, next) => void` pattern.
56
+ */
57
+ export type MoleculeRequestHandler = (req: MoleculeRequest, res: MoleculeResponse, next: MoleculeNextFunction) => void | Promise<void>;
58
+ //# sourceMappingURL=http-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-types.d.ts","sourceRoot":"","sources":["../src/http-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,GAAG,CAAA;IACT,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC9B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;IACtD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAChC;;;;OAIG;IACH,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,GAAG,IAAI,CAAA;CACjE;AAED;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAA;IACzB,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAA;IACzB,GAAG,IAAI,IAAI,CAAA;IACX,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAA;IAC1C,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5C,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;IAC5E,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;IACtC,YAAY,CAAC,IAAI,IAAI,CAAA;IACrB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAC5B;AAED;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;AAE1D;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,CACnC,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,oBAAoB,KACvB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Framework-agnostic HTTP types for molecule.dev resource handlers.
3
+ *
4
+ * These are structural subtypes of Express types — Express objects satisfy them
5
+ * without adapters. Allows resource handlers to be used with any HTTP framework
6
+ * (Express, Fastify, Hono, etc.) by depending on these interfaces instead of Express directly.
7
+ *
8
+ * @module
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=http-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-types.js","sourceRoot":"","sources":["../src/http-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"}
package/dist/i18n.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Locale registration for the resource package.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * Sentinel value confirming that locale translations for the resource package
8
+ * have been registered (or attempted). Always `true` after this module loads.
9
+ */
10
+ export declare const i18nRegistered = true;
11
+ //# sourceMappingURL=i18n.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAWH;;;GAGG;AACH,eAAO,MAAM,cAAc,OAAO,CAAA"}
package/dist/i18n.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Locale registration for the resource package.
3
+ *
4
+ * @module
5
+ */
6
+ import { registerLocaleModule } from '@molecule/api-i18n';
7
+ try {
8
+ const locales = await import('@molecule/api-locales-resource');
9
+ registerLocaleModule(locales);
10
+ }
11
+ catch (_error) {
12
+ // Locale package not available (not built or not installed).
13
+ }
14
+ /**
15
+ * Sentinel value confirming that locale translations for the resource package
16
+ * have been registered (or attempted). Always `true` after this module loads.
17
+ */
18
+ export const i18nRegistered = true;
19
+ //# sourceMappingURL=i18n.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i18n.js","sourceRoot":"","sources":["../src/i18n.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAA;AAEzD,IAAI,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,gCAAgC,CAAC,CAAA;IAC9D,oBAAoB,CAAC,OAAO,CAAC,CAAA;AAC/B,CAAC;AAAC,OAAO,MAAM,EAAE,CAAC;IAChB,6DAA6D;AAC/D,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAA"}