@where-org/where-common 2.0.1

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
+ MIT License
2
+
3
+ Copyright (c) 2019-present, Masafumi Sasahara and contributors.
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 all
13
+ 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 THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # where-common
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './lib/types/cq.js';
2
+ export * from './lib/types/da.js';
3
+ export * from './lib/types/common.js';
4
+ export * from './lib/types/define.js';
5
+ export * from './lib/types/exception.js';
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './lib/common.js';
@@ -0,0 +1,147 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { lstat } from 'node:fs/promises';
4
+
5
+ import { read } from '../file/read.js';
6
+
7
+ const ext = { '.json': 'json', '.yaml': 'yaml', '.yml': 'yaml', };
8
+
9
+ const checkDependencies = (i, tree, key, original, chain = [original]) => {
10
+
11
+ if (key === original) {
12
+ throw new Error(`Circular dependency detected: ${chain.join(' -> ')} -> ${key}`);
13
+ }
14
+
15
+ if (!tree[key]) {
16
+ return i;
17
+ }
18
+
19
+ if (!tree[key].dep) {
20
+ return i + 1;
21
+ }
22
+
23
+ return Object.entries(tree[key].dep).
24
+ map(([k, v]) => checkDependencies(i + 1, tree, v, original, [...chain, key])).reduce((a, b) => Math.max(a, b));
25
+
26
+ };
27
+
28
+ /* resolve */
29
+ const resolve = async (dir, fileName) => {
30
+
31
+ const paths = Object.keys(ext).map(v => path.join(dir, fileName + v));
32
+
33
+ const configFilePath = await Promise.any(paths.map(async v => {
34
+
35
+ if (!(await lstat(v)).isFile()) {
36
+ throw new Error(`File not found: ${v}`);
37
+ }
38
+
39
+ return v;
40
+
41
+ }));
42
+
43
+ const key = ext[path.extname(configFilePath)];
44
+ return await read[key](configFilePath, true);
45
+
46
+ };
47
+
48
+ /* load */
49
+ const load = async (dir, mode, name, ignore = null) => {
50
+
51
+ const configFileName = [
52
+ { name, ignore: ignore ?? false },
53
+ { name: `${name}-app`, ignore: ignore ?? false },
54
+ { name: `${name}-spec`, ignore: ignore ?? true },
55
+ ];
56
+
57
+ const [commonConfig, appConfig, specConfig] = await Promise.all(configFileName.map(async v => {
58
+
59
+ const config = await resolve(dir, `${v.name}-${mode}`).catch(async err => {
60
+
61
+ if (err instanceof SyntaxError) {
62
+ throw err;
63
+ }
64
+
65
+ return await resolve(dir, v.name).catch(err => {
66
+
67
+ if (err instanceof SyntaxError) {
68
+ throw err;
69
+ }
70
+
71
+ return undefined;
72
+
73
+ });
74
+
75
+ });
76
+
77
+ if (!config) {
78
+
79
+ if (v.ignore) {
80
+ return {};
81
+ }
82
+
83
+ throw new Error(`Unable to resolve config: tried: ${v.name}-${mode}, ${v.name}`);
84
+
85
+ }
86
+
87
+ return config;
88
+
89
+ }));
90
+
91
+ // izon kankei wo shirabete sort shimasu.
92
+ // junkan sansho shiteiru baai ha error wo throw shimasu.
93
+
94
+ const sortedAppConfig = Object.entries(appConfig).reduce((o, [k1, v1]) => {
95
+
96
+ const { dep } = v1;
97
+
98
+ if (!dep) {
99
+ o[0] = { ...(o[0] || {}), [k1]: v1 };
100
+ return o;
101
+ }
102
+
103
+ const i = Object.entries(dep).
104
+ map(([, k2]) => checkDependencies(0, mergedAppConfig, k2, k1)).reduce((a, b) => Math.max(a, b));
105
+
106
+ o[i] = { ...(o[i] || {}), [k1]: v1 };
107
+ return o;
108
+
109
+ }, []).reduce((o, v) => {
110
+ return Object.entries(v).reduce((o, [k, v]) => ({ ...o, [k]: v }), o);
111
+
112
+ }, {});
113
+
114
+ return { [name]: commonConfig, app: sortedAppConfig, spec: specConfig };
115
+
116
+ };
117
+
118
+ /* mergeSpec */
119
+ const mergeSpec = async (appConfig, specConfig) => {
120
+
121
+ const mergedConfig = await Object.entries(appConfig).reduce(async (o, [k, v]) => {
122
+
123
+ if (k in specConfig) {
124
+ const { description, scope } = specConfig[k];
125
+ return { ...await o, [k]: { ...v, spec: { description, scope } } };
126
+ }
127
+
128
+ const packageConfigPath = path.join(path.dirname(fileURLToPath(v.importPath)), 'config');
129
+
130
+ const moduleSpec = await resolve(packageConfigPath, 'module-spec').catch(err => undefined);
131
+
132
+ if (!moduleSpec || !('description' in moduleSpec) || !('scope' in moduleSpec)) {
133
+ return { ...await o, [k]: v };
134
+ }
135
+
136
+ const { description, scope } = moduleSpec;
137
+
138
+ return { ...await o, [k]: { ...v, spec: { description, scope } } };
139
+
140
+ }, {});
141
+
142
+ return mergedConfig;
143
+
144
+ };
145
+
146
+
147
+ export { load, mergeSpec };
@@ -0,0 +1 @@
1
+ export * as config from './config.js'
@@ -0,0 +1,4 @@
1
+ import { read } from './read.js';
2
+
3
+ const file = { read, };
4
+ export { file };
@@ -0,0 +1,46 @@
1
+ import path from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+
4
+ import yaml from 'js-yaml';
5
+
6
+ const read = {
7
+
8
+ json: async (src, flat = false) => {
9
+
10
+ try {
11
+ const content = JSON.parse(await readFile(src));
12
+
13
+ return flat && Array.isArray(content)
14
+ ? content.reduce((o, v) => ({ ...o, ...v }), {})
15
+ : content;
16
+
17
+ } catch(err) {
18
+
19
+ if (err instanceof yaml.YAMLException) {
20
+ throw new SyntaxError(err.message);
21
+ }
22
+ throw err;
23
+
24
+ }
25
+ },
26
+
27
+ yaml: async (src, flat = false) => {
28
+
29
+ try {
30
+ const content = yaml.loadAll(await readFile(src));
31
+
32
+ return flat
33
+ ? content.reduce((o, v) => ({ ...o, ...v }), {})
34
+ : content;
35
+
36
+ } catch(err) {
37
+ if (err instanceof yaml.YAMLException) {
38
+ throw new SyntaxError(err.message);
39
+ }
40
+ throw err;
41
+ }
42
+ },
43
+
44
+ };
45
+
46
+ export { read };
@@ -0,0 +1,4 @@
1
+ import { init } from './init/index.js';
2
+ import { util } from './util/index.js';
3
+
4
+ export { init, util };
@@ -0,0 +1,7 @@
1
+ import { config } from './config/index.js';
2
+ import { file } from './file/index.js';
3
+ import { init } from './init/index.js';
4
+ import { spec } from './spec/index.js';
5
+ import { util } from './util/index.js';
6
+
7
+ export { config, file, init, spec, util, };
@@ -0,0 +1,65 @@
1
+ const credential = async ({ module, meta, ...rest }, dep) => {
2
+
3
+ const { dep: metaDep, scope: metaScope, key: metaKey, credential: metaCredential = 'credential', ...column } = meta || {},
4
+ { [metaDep]: db } = dep || {};
5
+
6
+ const request = async (key) => {
7
+
8
+ const res = (db) ? await db.get(metaScope, { where: { [metaKey]: key } }).catch(err => [rest[key]]) : [rest[key]],
9
+ [data] = (res.length) ? res : [rest[key]];
10
+
11
+ if (!data) {
12
+ return null;
13
+ }
14
+
15
+ return Object.entries(column).reduce((o, [k1, k2]) => {
16
+ const v = data[k2],
17
+ {[k2]: remove, ...rest} = o;
18
+
19
+ return (v === null || v === undefined) ? { ...rest } : { ...rest, [k1]: v };
20
+ }, data);
21
+
22
+ }
23
+
24
+ return {
25
+
26
+ keys: [
27
+ ...((db) ? await db.get(metaScope).catch(err => []) : []).map(v => v[metaKey]),
28
+ ...Object.keys(rest),
29
+ ],
30
+
31
+ // static
32
+ requestStaticCredential: async () => {
33
+ if (!rest[metaCredential]) {
34
+ throw new Error(`Credential is not fixed.`);
35
+ }
36
+
37
+ const credential = await request(metaCredential);
38
+
39
+ if (!credential) {
40
+ throw new Error('No credential.');
41
+ }
42
+
43
+ return credential;
44
+ },
45
+
46
+ // dynamic
47
+ requestCredential: async (key) => {
48
+ if (rest[metaCredential]) {
49
+ throw new Error(`Credential is fixed.`);
50
+ }
51
+
52
+ const credential = await request(key);
53
+
54
+ if (!credential) {
55
+ throw new Error('No credential.');
56
+ }
57
+
58
+ return credential;
59
+ }
60
+
61
+ };
62
+
63
+ }
64
+
65
+ export { credential };
@@ -0,0 +1,13 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ const emitter = () => {
4
+
5
+ const eventEmitter = new EventEmitter();
6
+
7
+ return ['on', 'off', 'once', 'emit'].reduce((o, k) => {
8
+ return { ...o, [k]: (...args) => eventEmitter[k](...args) };
9
+ }, {});
10
+
11
+ }
12
+
13
+ export { emitter };
@@ -0,0 +1,8 @@
1
+ import { credential } from './credential.js';
2
+ import { log } from './log.js';
3
+
4
+ const init = {
5
+ credential, log,
6
+ };
7
+
8
+ export { init };
@@ -0,0 +1,9 @@
1
+ import { credential } from './credential.js';
2
+ import { emitter } from './emitter.js';
3
+ import { log } from './log.js';
4
+
5
+ const init = {
6
+ credential, emitter, log,
7
+ };
8
+
9
+ export { init };
@@ -0,0 +1,14 @@
1
+ import { date } from '../util/date.js';
2
+
3
+ const log = (label, indent = false, out = 'error') => {
4
+
5
+ const { module, ...rest } = (typeof label === 'string') ? { module: label } : label;
6
+
7
+ return (o) => {
8
+ const log = (typeof o === 'string') ? { message: o }: o;
9
+ console[out](JSON.stringify({ date: date.string(new Date()), module, ...rest, ...log }, null, (indent) ? 2 : 0));
10
+ }
11
+
12
+ }
13
+
14
+ export { log };
@@ -0,0 +1,105 @@
1
+ defs:
2
+ schema: &schema
3
+ $schema:
4
+ type: string
5
+ x-scope-name:
6
+ type: string
7
+ title:
8
+ type: string
9
+ description:
10
+ type: string
11
+ type:
12
+ const: array
13
+ type: string
14
+ items:
15
+ type: object
16
+
17
+ condition: &condition
18
+ $schema:
19
+ type: string
20
+ x-scope-name:
21
+ type: string
22
+ title:
23
+ type: string
24
+ description:
25
+ type: string
26
+ type:
27
+ const: object
28
+ type: string
29
+ additionalProperties:
30
+ const: false
31
+ type: boolean
32
+ properties:
33
+ type: object
34
+ $defs:
35
+ type: object
36
+
37
+ scope: &scope
38
+ description: List of app scopes
39
+ type: array
40
+ items:
41
+ type: object
42
+ required: [name, schema, condition]
43
+ additionalProperties: false
44
+ properties:
45
+ name:
46
+ description: Scope name
47
+ type: string
48
+ method:
49
+ description: Supported HTTP methods
50
+ type: array
51
+ items:
52
+ type: string
53
+ enum: [GET, POST, PUT, DELETE]
54
+
55
+ schema:
56
+ description: Request and response schema in JSON Schema format
57
+ type: object
58
+ properties: *schema
59
+
60
+ condition:
61
+ description: Query condition schema in JSON Schema format
62
+ type: object
63
+ properties: *condition
64
+
65
+
66
+ scope:
67
+ - name: '@spec'
68
+ method: [GET]
69
+ schema:
70
+ title: '@spec'
71
+ description: Provides a list of available scopes, schemas, and query conditions.
72
+ type: array
73
+ items:
74
+ type: object
75
+ required: [description, scope]
76
+ additionalProperties: false
77
+ properties:
78
+
79
+ description:
80
+ description: App description
81
+ type: string
82
+ readOnly: true
83
+ scope: *scope
84
+
85
+ - name: '@schema'
86
+ method: [GET]
87
+ schema:
88
+ title: '@schema'
89
+ description: Request and response schema in JSON Schema format
90
+ type: array
91
+ items:
92
+ type: object
93
+ properties: *schema
94
+
95
+ - name: '@condition'
96
+ method: [GET]
97
+ schema:
98
+ title: '@condition'
99
+ description: Query condition schema in JSON Schema format
100
+ type: array
101
+ items:
102
+ type: object
103
+ additionalProperties: false
104
+ properties: *condition
105
+
@@ -0,0 +1 @@
1
+ export * as spec from './spec.js'
@@ -0,0 +1,206 @@
1
+ import path from 'node:path';
2
+ import { read } from '../file/read.js';
3
+
4
+ const [{ scope: at }] = (await read.yaml(path.resolve(import.meta.dirname, './at-spec.yaml'))).flat();
5
+
6
+ const properties = {
7
+
8
+ single: (type) => {
9
+ return { type };
10
+ },
11
+
12
+ oneOf: (type) => {
13
+ return {
14
+ oneOf: [
15
+ { type },
16
+ { type: 'array', items: { type } },
17
+ ],
18
+ };
19
+ },
20
+
21
+ array: (type) => {
22
+ return {
23
+ type: 'array',
24
+ items: { type },
25
+ minItems: 2,
26
+ maxItems: 2,
27
+ };
28
+ },
29
+
30
+ };
31
+
32
+ const operators = {
33
+
34
+ '=': ([k, op], v) => {
35
+ const description = 'Equal';
36
+ return { [k]: { description, ...properties.oneOf(v.type) } };
37
+ },
38
+
39
+ '!': ([k, op], v) => {
40
+ const description = 'Not equal';
41
+ return { [k + op]: { description, ...properties.oneOf(v.type) } };
42
+ },
43
+
44
+ '<': ([k, op], v) => {
45
+ const description = 'Less than';
46
+ return { [k + op]: { description, ...properties.single(v.type) } };
47
+ },
48
+
49
+ '>': ([k, op], v) => {
50
+ const description = 'Greater than';
51
+ return { [k + op]: { description, ...properties.single(v.type) } };
52
+ },
53
+
54
+ '<=': ([k, op], v) => {
55
+ const description = 'Less than or equal';
56
+ return { [k + op]: { description, ...properties.single(v.type) } };
57
+ },
58
+
59
+ '>=': ([k, op], v) => {
60
+ const description = 'Greater than or equal';
61
+ return { [k + op]: { description, ...properties.single(v.type) } };
62
+ },
63
+
64
+ '-': ([k, op], v) => {
65
+ const description = 'Between range';
66
+ return { [k + op]: { description, ...properties.array(v.type) } };
67
+ },
68
+
69
+ '*': ([k, op], v) => {
70
+ const description = 'Partial match (LIKE). Supports wildcard "*". "*value*" for contains, "value*" for prefix, "*value" for suffix. Without "*", treated as exact match.';
71
+ return { [k + op]: { description, ...properties.single(v.type) } };
72
+ },
73
+
74
+ '!*': ([k, op], v) => {
75
+ const description = 'Partial not match (NOT LIKE). Supports wildcard "*". "*value*" for contains, "value*" for prefix, "*value" for suffix. Without "*", treated as exact match.';
76
+ return { [k + op]: { description, ...properties.single(v.type) } };
77
+ },
78
+
79
+ };
80
+
81
+ const fromConfig = async (name, spec = {}) => {
82
+
83
+ const scope = !('scope' in spec) ? {} : { scope: [...spec.scope, ...at].map(v => {
84
+
85
+ const schema = {
86
+ '$schema': 'https://json-schema.org/draft/2020-12/schema',
87
+ 'x-scope-name': v.name,
88
+ ...v.schema ?? {},
89
+ };
90
+
91
+ const where = Object.entries(schema.items.properties).reduce((o, [k, v]) => {
92
+
93
+ if (['array', 'object'].includes(v.type) || v.writeOnly) {
94
+ return o;
95
+ }
96
+
97
+ return Object.entries(operators).reduce((o, [op, f]) => {
98
+ return { ...o, ...f([k, op], v) };
99
+ }, o);
100
+
101
+ }, {});
102
+
103
+ const condition = {
104
+ '$schema': 'https://json-schema.org/draft/2020-12/schema',
105
+ 'x-scope-name': v.name,
106
+
107
+ title: 'condition',
108
+ description: 'Query conditions for filtering, sorting, and paginating results',
109
+
110
+ type: 'object',
111
+ additionalProperties: false,
112
+
113
+ properties: {
114
+
115
+ select: {
116
+ description: 'Array of column names to retrieve',
117
+ type: 'array',
118
+ items: {
119
+ type: 'string',
120
+ enum: Object.keys(schema.items.properties),
121
+ },
122
+ uniqueItems: true,
123
+ minItems: 1,
124
+ },
125
+
126
+ where: {
127
+ description: 'Filter conditions',
128
+ oneOf: [
129
+ {
130
+ description: 'AND conditions',
131
+ '$ref': '#/$defs/where',
132
+ },
133
+
134
+ {
135
+ description: 'OR conditions',
136
+ type: 'object',
137
+ properties: {
138
+ or: {
139
+ type: 'array',
140
+ items: { '$ref': '#/$defs/where' },
141
+ },
142
+ },
143
+ required: ['or'],
144
+ additionalProperties: false,
145
+ },
146
+
147
+ ]
148
+ },
149
+
150
+ order: {
151
+ description: 'Sort order',
152
+ type: 'object',
153
+ additionalProperties: false,
154
+
155
+ properties: Object.entries(schema.items.properties).reduce((o, [k, v]) => {
156
+
157
+ if (['array', 'object'].includes(v.type) || v.writeOnly) {
158
+ return o;
159
+ }
160
+
161
+ const { description } = v;
162
+ return { ...o, [k]: { description, type: 'string', enum: ['asc', 'desc'] } };
163
+
164
+ }, {}),
165
+
166
+ },
167
+
168
+ limit: {
169
+ description: 'Pagination',
170
+ type: 'object',
171
+ additionalProperties: false,
172
+ properties: {
173
+ offset: {
174
+ description: 'Number of rows to skip',
175
+ type: 'integer',
176
+ },
177
+ limit: {
178
+ description: 'Maximum number of rows to return',
179
+ type: 'integer',
180
+ },
181
+ },
182
+ },
183
+
184
+ },
185
+
186
+ '$defs': {
187
+
188
+ where: {
189
+ type: 'object',
190
+ additionalProperties: false,
191
+ properties: where,
192
+ },
193
+
194
+ },
195
+
196
+ };
197
+
198
+ return { ...v, schema, condition };
199
+
200
+ })};
201
+
202
+ return { ...spec, ...scope };
203
+
204
+ };
205
+
206
+ export { fromConfig };