inanis 0.0.7-beta.7 → 0.0.7-beta.9

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 (47) hide show
  1. package/dist/api/context.js +16 -23
  2. package/dist/api/export-open-api.js +3 -7
  3. package/dist/api/index.d.ts +2 -2
  4. package/dist/api/index.js +16 -20
  5. package/dist/api/method.d.ts +2 -2
  6. package/dist/api/method.js +13 -17
  7. package/dist/api/middleware.js +1 -5
  8. package/dist/api/router.js +10 -14
  9. package/dist/auth/index.js +15 -19
  10. package/dist/auth/jwt.js +7 -14
  11. package/dist/auth/oauth.js +17 -27
  12. package/dist/build-tools/exec.js +7 -14
  13. package/dist/build-tools/fs.js +5 -12
  14. package/dist/build-tools/index.js +8 -44
  15. package/dist/build-tools/swagger-to-types.js +7 -44
  16. package/dist/build-tools/yaml.js +6 -14
  17. package/dist/document-db/index.js +16 -53
  18. package/dist/document-db/table-dynamo.js +15 -19
  19. package/dist/document-db/table-mongo.js +6 -10
  20. package/dist/document-db/table.js +10 -14
  21. package/dist/exception.js +3 -6
  22. package/dist/index.d.ts +9 -9
  23. package/dist/index.js +17 -70
  24. package/dist/main.d.ts +8 -8
  25. package/dist/main.js +6 -10
  26. package/dist/memory-db/index.js +4 -41
  27. package/dist/message/index.js +13 -17
  28. package/dist/message/message.js +12 -17
  29. package/dist/modules/data-model.js +5 -11
  30. package/dist/modules/rabbit-mq.js +5 -42
  31. package/dist/modules/request.js +7 -14
  32. package/dist/modules/warm-up.js +5 -9
  33. package/dist/schedule/context.js +3 -7
  34. package/dist/schedule/index.js +8 -12
  35. package/dist/schedule/unit.js +12 -49
  36. package/dist/storage/index.js +24 -31
  37. package/dist/time.js +3 -10
  38. package/dist/types.js +1 -2
  39. package/dist/utils/errors.js +1 -10
  40. package/dist/utils/json-schema.js +3 -7
  41. package/dist/utils/output.js +3 -10
  42. package/dist/utils/string.js +4 -9
  43. package/dist/utils/validate.js +4 -8
  44. package/dist/websocket/emitter.js +1 -5
  45. package/dist/websocket/index.js +15 -52
  46. package/package.json +3 -2
  47. package/tsconfig.json +2 -2
@@ -1,17 +1,11 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RouterContext = void 0;
7
- const querystring_1 = __importDefault(require("querystring"));
8
- const power_helper_1 = require("power-helper");
9
- const validate_js_1 = require("../utils/validate.js");
10
- const power_helper_2 = require("power-helper");
11
- const exception_js_1 = require("../exception.js");
12
- const errors_js_1 = require("../utils/errors.js");
13
- const exception = exception_js_1.rootException.checkout('Api/Context');
14
- class RouterContext {
1
+ import querystring from 'querystring';
2
+ import { json, Hook } from 'power-helper';
3
+ import { validate } from '../utils/validate.js';
4
+ import { Interaction } from 'power-helper';
5
+ import { rootException } from '../exception.js';
6
+ import { ValidationError, AnyError, UnknowError } from '../utils/errors.js';
7
+ const exception = rootException.checkout('Api/Context');
8
+ export class RouterContext {
15
9
  ip = '';
16
10
  data;
17
11
  meta = {};
@@ -24,7 +18,7 @@ class RouterContext {
24
18
  params;
25
19
  language;
26
20
  method;
27
- hook = new power_helper_1.Hook();
21
+ hook = new Hook();
28
22
  headers = {};
29
23
  failMessages;
30
24
  interaction;
@@ -33,7 +27,7 @@ class RouterContext {
33
27
  export = null;
34
28
  constructor(method) {
35
29
  this.method = method;
36
- this.interaction = new power_helper_2.Interaction({
30
+ this.interaction = new Interaction({
37
31
  name: `${this.method.action}@${this.method.router.path}`,
38
32
  interceptorMessage: (data) => data
39
33
  });
@@ -81,10 +75,10 @@ class RouterContext {
81
75
  context.file = Buffer.from(event.body, 'base64');
82
76
  }
83
77
  else if (method.contentType === 'application/x-www-form-urlencoded') {
84
- context.body = querystring_1.default.parse(event.body);
78
+ context.body = querystring.parse(event.body);
85
79
  }
86
80
  else {
87
- context.body = power_helper_1.json.nonStrictJSONParse(event.body || '{}');
81
+ context.body = json.nonStrictJSONParse(event.body || '{}');
88
82
  }
89
83
  return context;
90
84
  }
@@ -94,10 +88,10 @@ class RouterContext {
94
88
  _validate() {
95
89
  try {
96
90
  if (this.method.verify.body) {
97
- this.body = (0, validate_js_1.validate)(this.body, this.method.verify.body);
91
+ this.body = validate(this.body, this.method.verify.body);
98
92
  }
99
93
  if (this.method.verify.query) {
100
- this.query = (0, validate_js_1.validate)(this.query, this.method.verify.query);
94
+ this.query = validate(this.query, this.method.verify.query);
101
95
  }
102
96
  }
103
97
  catch (error) {
@@ -121,7 +115,7 @@ class RouterContext {
121
115
  });
122
116
  }
123
117
  validateError(error) {
124
- const e = new errors_js_1.ValidationError();
118
+ const e = new ValidationError();
125
119
  this.response(e.statusCode, false, {
126
120
  code: 'ValidateError',
127
121
  desc: '',
@@ -134,7 +128,7 @@ class RouterContext {
134
128
  }
135
129
  /** 完全是在例外中錯誤 */
136
130
  autoError(error) {
137
- let e = error instanceof errors_js_1.AnyError ? error : new errors_js_1.UnknowError();
131
+ let e = error instanceof AnyError ? error : new UnknowError();
138
132
  this.response(e.statusCode, false, {
139
133
  code: 'EmptyError',
140
134
  desc: '',
@@ -203,4 +197,3 @@ class RouterContext {
203
197
  };
204
198
  }
205
199
  }
206
- exports.RouterContext = RouterContext;
@@ -1,8 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.exportOpenApi = void 0;
4
- const output_js_1 = require("../utils/output.js");
5
- const exportOpenApi = async (router, swaggerParams) => {
1
+ import { toOutputData } from '../utils/output.js';
2
+ export const exportOpenApi = async (router, swaggerParams) => {
6
3
  const routes = router.export();
7
4
  const securitySchemes = {};
8
5
  const output = {
@@ -55,6 +52,5 @@ const exportOpenApi = async (router, swaggerParams) => {
55
52
  }
56
53
  }
57
54
  }
58
- return (0, output_js_1.toOutputData)(output);
55
+ return toOutputData(output);
59
56
  };
60
- exports.exportOpenApi = exportOpenApi;
@@ -4,7 +4,7 @@ import { exportOpenApi } from './export-open-api.js';
4
4
  import { Router, RouterParams, Methods } from './router.js';
5
5
  import { RouterContext, RouterContextExport } from './context.js';
6
6
  import { AnyError } from '../utils/errors.js';
7
- import { APIGatewayProxyHandler } from 'aws-lambda';
7
+ import { APIGatewayEvent } from 'aws-lambda';
8
8
  export type FailData = Record<string, {
9
9
  desc: string;
10
10
  error: typeof AnyError;
@@ -47,7 +47,7 @@ export declare class APIManager extends Event<Channels> {
47
47
  method: string;
48
48
  handler: (..._args: any[]) => void;
49
49
  }[];
50
- lambdaHandler: () => Record<string, APIGatewayProxyHandler>;
50
+ lambdaHandler: () => Record<string, (_event: APIGatewayEvent) => any>;
51
51
  serverlessFunctionsConfig: (params?: {
52
52
  handler: (group: any) => any;
53
53
  }) => Promise<{
package/dist/api/index.js CHANGED
@@ -1,14 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APIManager = void 0;
4
- const power_helper_1 = require("power-helper");
5
- const build_tools_1 = require("../build-tools");
6
- const output_js_1 = require("../utils/output.js");
7
- const exception_js_1 = require("../exception.js");
8
- const export_open_api_js_1 = require("./export-open-api.js");
9
- const router_js_1 = require("./router.js");
10
- const string_js_1 = require("../utils/string.js");
11
- const exception = exception_js_1.rootException.checkout('APIManager');
1
+ import { Event } from 'power-helper';
2
+ import { buildTools } from '../build-tools/index.js';
3
+ import { toOutputData } from '../utils/output.js';
4
+ import { rootException } from '../exception.js';
5
+ import { exportOpenApi } from './export-open-api.js';
6
+ import { Router } from './router.js';
7
+ import { toRouterName } from '../utils/string.js';
8
+ const exception = rootException.checkout('APIManager');
12
9
  const getLambdaGroup = (manager, method, path) => {
13
10
  let sourcePath = `${method}@${path}`;
14
11
  let group = manager.params.awsLambda?.groups?.find(e => {
@@ -25,7 +22,7 @@ const getLambdaGroup = (manager, method, path) => {
25
22
  return false;
26
23
  });
27
24
  if (group) {
28
- const name = (0, string_js_1.toRouterName)(group.paths[0].split('@').slice(1).join()) + 'Group';
25
+ const name = toRouterName(group.paths[0].split('@').slice(1).join()) + 'Group';
29
26
  return {
30
27
  name: `${name}ApiGroup`,
31
28
  handler: `src/index.${name}`,
@@ -40,7 +37,7 @@ const getLambdaGroup = (manager, method, path) => {
40
37
  handlerName: `${method}${router.name}`
41
38
  };
42
39
  };
43
- class APIManager extends power_helper_1.Event {
40
+ export class APIManager extends Event {
44
41
  params;
45
42
  inanis = null;
46
43
  routers = [];
@@ -55,7 +52,7 @@ class APIManager extends power_helper_1.Event {
55
52
  });
56
53
  }
57
54
  createRoute(params) {
58
- const route = new router_js_1.Router(this, params);
55
+ const route = new Router(this, params);
59
56
  this.routers.push(route);
60
57
  return route;
61
58
  }
@@ -112,14 +109,14 @@ class APIManager extends power_helper_1.Event {
112
109
  const outputs = [];
113
110
  const openApi = await this.outputs.openApiDocument({ servers: [] });
114
111
  for (let doc in openApi) {
115
- outputs.push(await build_tools_1.buildTools.swaggerToTypes(doc, openApi[doc].yaml));
112
+ outputs.push(await buildTools.swaggerToTypes(doc, openApi[doc].yaml));
116
113
  }
117
114
  return outputs.join('\n\n');
118
115
  },
119
116
  openApiDocument: async (params) => {
120
117
  const outputs = {};
121
118
  for (let router of this.routers) {
122
- outputs[router.name] = await (0, export_open_api_js_1.exportOpenApi)(router, params);
119
+ outputs[router.name] = await exportOpenApi(router, params);
123
120
  }
124
121
  return outputs;
125
122
  },
@@ -143,7 +140,7 @@ class APIManager extends power_helper_1.Event {
143
140
  this.eachMethods((router, method) => {
144
141
  const group = getLambdaGroup(this, method, router.path);
145
142
  if (outputs[group.handlerName] == null) {
146
- outputs[group.handlerName] = (event, context, callback) => {
143
+ outputs[group.handlerName] = async (event) => {
147
144
  let callPath = event.requestContext.resourcePath;
148
145
  let isOffline = !!this.params.serverless?.isOffline;
149
146
  if (isOffline) {
@@ -154,7 +151,7 @@ class APIManager extends power_helper_1.Event {
154
151
  throw exception.create('No Method Found');
155
152
  }
156
153
  const handler = method.outputs.lambdaHandler();
157
- return handler(event, context, callback);
154
+ return handler(event);
158
155
  };
159
156
  }
160
157
  });
@@ -186,9 +183,8 @@ class APIManager extends power_helper_1.Event {
186
183
  http: m.outputs.getServerlessHttp()
187
184
  });
188
185
  });
189
- return (0, output_js_1.toOutputData)(outputs);
186
+ return toOutputData(outputs);
190
187
  }
191
188
  };
192
189
  }
193
190
  }
194
- exports.APIManager = APIManager;
@@ -1,7 +1,7 @@
1
1
  import { Router } from './router.js';
2
2
  import { FailData } from './index.js';
3
3
  import { RouterContext, RouterContextExport } from './context.js';
4
- import { APIGatewayProxyHandler } from 'aws-lambda';
4
+ import { APIGatewayEvent } from 'aws-lambda';
5
5
  import { ValidateCallback, ValidateCallbackOutputs } from '../utils/validate.js';
6
6
  import { MiddlewareExport } from './middleware.js';
7
7
  import type { Handler } from 'express';
@@ -65,7 +65,7 @@ export declare class Method<Path extends string = any, Fails extends FailData =
65
65
  run(context: RouterContext): Promise<RouterContextExport>;
66
66
  get outputs(): {
67
67
  expressHandler: () => Handler;
68
- lambdaHandler: () => APIGatewayProxyHandler;
68
+ lambdaHandler: () => (event: APIGatewayEvent) => Promise<unknown>;
69
69
  getServerlessHttp: () => {
70
70
  cors: {
71
71
  origin: string;
@@ -1,16 +1,13 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Method = void 0;
4
- const zod_1 = require("zod");
5
- const power_helper_1 = require("power-helper");
6
- const json_schema_js_1 = require("../utils/json-schema.js");
7
- const context_js_1 = require("./context.js");
1
+ import { z } from 'zod';
2
+ import { pick, array } from 'power-helper';
3
+ import { zodToJsonSchema } from '../utils/json-schema.js';
4
+ import { RouterContext } from './context.js';
8
5
  const headers = {
9
6
  'Content-Type': 'application/json;charset=utf-8',
10
7
  'Access-Control-Allow-Origin': '*',
11
8
  'Access-Control-Allow-Credentials': 'true'
12
9
  };
13
- class Method {
10
+ export class Method {
14
11
  action;
15
12
  router;
16
13
  contentType;
@@ -49,7 +46,7 @@ class Method {
49
46
  get allowHeaders() {
50
47
  const routerHeaders = this.fullRouters.map(router => router.allowHeaders).flat();
51
48
  const middlewaresHeaders = this.middlewares ? Object.values(this.middlewares(null)).map(middleware => middleware.self.allowHeaders).flat() : [];
52
- return power_helper_1.array.unique([...routerHeaders, ...middlewaresHeaders]);
49
+ return array.unique([...routerHeaders, ...middlewaresHeaders]);
53
50
  }
54
51
  async run(context) {
55
52
  try {
@@ -123,7 +120,7 @@ class Method {
123
120
  });
124
121
  return;
125
122
  }
126
- const context = await context_js_1.RouterContext.fromExpress(this, req);
123
+ const context = await RouterContext.fromExpress(this, req);
127
124
  const exp = await this.run(context);
128
125
  for (let [key, value] of Object.entries(headers)) {
129
126
  res.setHeader(key, value);
@@ -153,7 +150,7 @@ class Method {
153
150
  })
154
151
  });
155
152
  }
156
- const context = await context_js_1.RouterContext.fromAwsLambda(this, event);
153
+ const context = await RouterContext.fromAwsLambda(this, event);
157
154
  const state = {
158
155
  isCalled: false
159
156
  };
@@ -240,7 +237,7 @@ class Method {
240
237
  const bodySchemaBindDoc = (schema, doc) => {
241
238
  if (doc && doc.descs) {
242
239
  for (let key in doc.descs) {
243
- let target = power_helper_1.pick.peel(schema.properties, key.replaceAll('.', '.properties.'));
240
+ let target = pick.peel(schema.properties, key.replaceAll('.', '.properties.'));
244
241
  if (target && target !== true) {
245
242
  target.description = doc.descs[key];
246
243
  }
@@ -287,7 +284,7 @@ class Method {
287
284
  [this.router.nowAuthorizerExpression.name]: []
288
285
  });
289
286
  }
290
- const pathParams = power_helper_1.pick.vars({
287
+ const pathParams = pick.vars({
291
288
  start: '{',
292
289
  end: '}',
293
290
  text: this.router.path
@@ -306,7 +303,7 @@ class Method {
306
303
  });
307
304
  }
308
305
  if (this.verify.query) {
309
- const attrs = this.verify.query(zod_1.z);
306
+ const attrs = this.verify.query(z);
310
307
  for (let key in attrs) {
311
308
  const doc = docs.query?.[key] || {};
312
309
  const schema = attrs[key];
@@ -342,7 +339,7 @@ class Method {
342
339
  }
343
340
  else {
344
341
  const doc = docs.body;
345
- const schema = bodySchemaBindDoc((0, json_schema_js_1.zodToJsonSchema)(this.verify.body), doc);
342
+ const schema = bodySchemaBindDoc(zodToJsonSchema(this.verify.body), doc);
346
343
  output.requestBody = {
347
344
  content: {
348
345
  [this.contentType]: {
@@ -392,7 +389,7 @@ class Method {
392
389
  }
393
390
  if (this.verify.response) {
394
391
  const doc = docs.response;
395
- const jsonSchema = (0, json_schema_js_1.zodToJsonSchema)(z => {
392
+ const jsonSchema = zodToJsonSchema(z => {
396
393
  return {
397
394
  data: z.object(this.verify.response(z)).required()
398
395
  };
@@ -425,4 +422,3 @@ class Method {
425
422
  };
426
423
  }
427
424
  }
428
- exports.Method = Method;
@@ -1,8 +1,5 @@
1
- "use strict";
2
1
  /* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.Middleware = void 0;
5
- class Middleware {
2
+ export class Middleware {
6
3
  failMessages;
7
4
  allowHeaders = [];
8
5
  handler;
@@ -19,4 +16,3 @@ class Middleware {
19
16
  };
20
17
  }
21
18
  }
22
- exports.Middleware = Middleware;
@@ -1,11 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Router = void 0;
4
- const power_helper_1 = require("power-helper");
5
- const method_js_1 = require("./method.js");
6
- const validate_js_1 = require("../utils/validate.js");
7
- const string_js_1 = require("../utils/string.js");
8
- class Router {
1
+ import { array } from 'power-helper';
2
+ import { Method } from './method.js';
3
+ import { definedValidateSchema } from '../utils/validate.js';
4
+ import { toRouterName } from '../utils/string.js';
5
+ export class Router {
9
6
  tags;
10
7
  path;
11
8
  manager;
@@ -26,18 +23,18 @@ class Router {
26
23
  this.authorizerExpression = params.authorizerExpression;
27
24
  }
28
25
  get name() {
29
- return (0, string_js_1.toRouterName)(this.path);
26
+ return toRouterName(this.path);
30
27
  }
31
28
  get fullTags() {
32
29
  if (this.parent) {
33
- return power_helper_1.array.unique([...this.parent.fullTags, ...this.tags]);
30
+ return array.unique([...this.parent.fullTags, ...this.tags]);
34
31
  }
35
32
  else {
36
- return power_helper_1.array.unique(this.tags);
33
+ return array.unique(this.tags);
37
34
  }
38
35
  }
39
36
  get schema() {
40
- return validate_js_1.definedValidateSchema;
37
+ return definedValidateSchema;
41
38
  }
42
39
  get nowAuthorizerExpression() {
43
40
  if (this.authorizerExpression) {
@@ -88,9 +85,8 @@ class Router {
88
85
  // Method
89
86
  //
90
87
  method(key, params) {
91
- let method = new method_js_1.Method(this, key, params);
88
+ let method = new Method(this, key, params);
92
89
  this.methods[key] = method;
93
90
  return method;
94
91
  }
95
92
  }
96
- exports.Router = Router;
@@ -1,14 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AuthManager = void 0;
4
- const jwt_js_1 = require("./jwt.js");
5
- const change_case_1 = require("change-case");
6
- const output_js_1 = require("../utils/output.js");
7
- const exception_js_1 = require("../exception.js");
8
- const oauth_js_1 = require("./oauth.js");
9
- const exception = exception_js_1.rootException.checkout('auth/index');
10
- class AuthManager {
11
- jwt = new jwt_js_1.JWT(this);
1
+ import { JWT } from './jwt.js';
2
+ import { pascalCase } from 'change-case';
3
+ import { toOutputData } from '../utils/output.js';
4
+ import { rootException } from '../exception.js';
5
+ import { google, apple } from './oauth.js';
6
+ const exception = rootException.checkout('auth/index');
7
+ export class AuthManager {
8
+ jwt = new JWT(this);
12
9
  config;
13
10
  params;
14
11
  inanis;
@@ -27,14 +24,14 @@ class AuthManager {
27
24
  }
28
25
  toApiExpression() {
29
26
  return {
30
- name: `Authorizer${(0, change_case_1.pascalCase)(this.params.name)}`,
27
+ name: `Authorizer${pascalCase(this.params.name)}`,
31
28
  header: this.params.keySite.api,
32
29
  description: this.params.description || ''
33
30
  };
34
31
  }
35
32
  toWebsocketExpression() {
36
33
  return {
37
- name: `Authorizer${(0, change_case_1.pascalCase)(this.params.name)}`,
34
+ name: `Authorizer${pascalCase(this.params.name)}`,
38
35
  queryKey: this.params.keySite.websocket
39
36
  };
40
37
  }
@@ -50,7 +47,7 @@ class AuthManager {
50
47
  if (params.service === 'google') {
51
48
  let { googleAuthClientIds } = this.config.services.google;
52
49
  try {
53
- let payload = await (0, oauth_js_1.google)({
50
+ let payload = await google({
54
51
  idToken: params.token,
55
52
  audience: googleAuthClientIds
56
53
  });
@@ -67,7 +64,7 @@ class AuthManager {
67
64
  if (params.service === 'apple') {
68
65
  let { teamId, serviceId, appBundleId, keyId, key, redirectUri } = this.config.services.apple;
69
66
  try {
70
- let payload = await (0, oauth_js_1.apple)({
67
+ let payload = await apple({
71
68
  code: params.token,
72
69
  mode: params.mode,
73
70
  teamId,
@@ -114,14 +111,14 @@ class AuthManager {
114
111
  serverlessFunctionsConfig: () => {
115
112
  const config = {
116
113
  AuthorizerBasic: {
117
- handler: `src/index.authorizer${(0, change_case_1.pascalCase)(this.params.name)}`
114
+ handler: `src/index.authorizer${pascalCase(this.params.name)}`
118
115
  }
119
116
  };
120
- return (0, output_js_1.toOutputData)(config);
117
+ return toOutputData(config);
121
118
  },
122
119
  lambdaHandler: () => {
123
120
  return {
124
- [`authorizer${(0, change_case_1.pascalCase)(this.params.name)}`]: async (event) => {
121
+ [`authorizer${pascalCase(this.params.name)}`]: async (event) => {
125
122
  await this.inanis._install();
126
123
  try {
127
124
  // 暖機不作身份驗證
@@ -148,4 +145,3 @@ class AuthManager {
148
145
  };
149
146
  }
150
147
  }
151
- exports.AuthManager = AuthManager;
package/dist/auth/jwt.js CHANGED
@@ -1,13 +1,7 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.JWT = void 0;
7
- const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
- const exception_js_1 = require("../exception.js");
9
- const exception = exception_js_1.rootException.checkout('auth/jwt');
10
- class JWT {
1
+ import jwt from 'jsonwebtoken';
2
+ import { rootException } from '../exception.js';
3
+ const exception = rootException.checkout('auth/jwt');
4
+ export class JWT {
11
5
  cert;
12
6
  manager;
13
7
  constructor(manager) {
@@ -18,7 +12,7 @@ class JWT {
18
12
  }
19
13
  sign(data) {
20
14
  if (this.cert) {
21
- return jsonwebtoken_1.default.sign(data, this.cert, {
15
+ return jwt.sign(data, this.cert, {
22
16
  expiresIn: this.manager.params.expiresIn
23
17
  });
24
18
  }
@@ -28,7 +22,7 @@ class JWT {
28
22
  }
29
23
  decode(token) {
30
24
  if (this.cert) {
31
- return this.manager.params.readPayload(jsonwebtoken_1.default.decode(token));
25
+ return this.manager.params.readPayload(jwt.decode(token));
32
26
  }
33
27
  else {
34
28
  throw exception.create('Cert no setting.');
@@ -37,7 +31,7 @@ class JWT {
37
31
  verify(token) {
38
32
  if (this.cert) {
39
33
  return new Promise((resolve, reject) => {
40
- jsonwebtoken_1.default.verify(token, this.cert, (error, data) => {
34
+ jwt.verify(token, this.cert, (error, data) => {
41
35
  if (error) {
42
36
  reject(error);
43
37
  }
@@ -52,4 +46,3 @@ class JWT {
52
46
  }
53
47
  }
54
48
  }
55
- exports.JWT = JWT;
@@ -1,16 +1,10 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.apple = exports.fb = exports.google = exports.wechat = void 0;
7
- const qs_1 = __importDefault(require("qs"));
8
- const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
9
- const node_rsa_1 = __importDefault(require("node-rsa"));
10
- const request_js_1 = require("../modules/request.js");
11
- const google_auth_library_1 = require("google-auth-library");
12
- const wechat = async (params) => {
13
- const request = new request_js_1.Request();
1
+ import qs from 'qs';
2
+ import jwt from 'jsonwebtoken';
3
+ import NodeRSA from 'node-rsa';
4
+ import { Request } from '../modules/request.js';
5
+ import { OAuth2Client } from 'google-auth-library';
6
+ export const wechat = async (params) => {
7
+ const request = new Request();
14
8
  const APP_ID = params.appid;
15
9
  const APP_SECRET = params.secret;
16
10
  /** 驗證 */
@@ -36,7 +30,6 @@ const wechat = async (params) => {
36
30
  });
37
31
  return data;
38
32
  };
39
- exports.wechat = wechat;
40
33
  /**
41
34
  * google 驗證
42
35
  * @see https://developers.google.com/identity/gsi/web/guides/verify-google-id-token?hl=zh-tw
@@ -44,8 +37,8 @@ exports.wechat = wechat;
44
37
  * @see https://console.cloud.google.com/apis/credentials
45
38
  * @param {string} idToken app 登入後獲取的 token,由前端傳送
46
39
  */
47
- const google = async (params) => {
48
- const client = new google_auth_library_1.OAuth2Client();
40
+ export const google = async (params) => {
41
+ const client = new OAuth2Client();
49
42
  const ticket = await client.verifyIdToken({
50
43
  idToken: params.idToken,
51
44
  audience: params.audience
@@ -53,7 +46,6 @@ const google = async (params) => {
53
46
  const payload = ticket.getPayload();
54
47
  return payload;
55
48
  };
56
- exports.google = google;
57
49
  /**
58
50
  * facebook 驗證
59
51
  * @see https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow?locale=zh_TW
@@ -61,8 +53,8 @@ exports.google = google;
61
53
  * @see https://developers.facebook.com/apps/746067680583596/settings/basic/?business_id=2614394112203347
62
54
  * @param {string} token 生產用來交換 token 的 code,由前端傳送
63
55
  */
64
- const fb = async (param) => {
65
- const request = new request_js_1.Request();
56
+ export const fb = async (param) => {
57
+ const request = new Request();
66
58
  const cliendId = param.cliendId;
67
59
  const clientSecret = param.clientSecret;
68
60
  const accessTokenResponse = await request.axios.get('https://graph.facebook.com/oauth/access_token', {
@@ -91,14 +83,13 @@ const fb = async (param) => {
91
83
  const profile = await request.axios.get(profileUrl);
92
84
  return profile.data;
93
85
  };
94
- exports.fb = fb;
95
86
  /**
96
87
  * apple 驗證
97
88
  * @see https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens
98
89
  * @param {string} authorizationCode 生產用來交換 token 的 code,由前端傳送
99
90
  */
100
- const apple = async (param) => {
101
- const request = new request_js_1.Request();
91
+ export const apple = async (param) => {
92
+ const request = new Request();
102
93
  /**
103
94
  * 這裡跟 Web 驗證有不同,Web 是吃 Service ID,而 App 是吃 apple store 上的 app id(套件識別碼)
104
95
  * @see https://appstoreconnect.apple.com/apps/6450915707/appstore/info
@@ -127,14 +118,14 @@ const apple = async (param) => {
127
118
  iat: timeNow,
128
119
  exp: timeNow + 15777000
129
120
  };
130
- const clientSecret = jsonwebtoken_1.default.sign(claims, key, {
121
+ const clientSecret = jwt.sign(claims, key, {
131
122
  algorithm: 'ES256',
132
123
  header: {
133
124
  alg: 'ES256',
134
125
  kid: keyId
135
126
  }
136
127
  });
137
- const tokenResponse = await request.axios.post('https://appleid.apple.com/auth/token', qs_1.default.stringify({
128
+ const tokenResponse = await request.axios.post('https://appleid.apple.com/auth/token', qs.stringify({
138
129
  grant_type: 'authorization_code',
139
130
  code: param.code,
140
131
  client_id: clientId,
@@ -154,13 +145,13 @@ const apple = async (param) => {
154
145
  // 用來解碼的 key 有不只一組,每次可以用哪一組解開不確定,所以都跑,如果有成功的就 break
155
146
  for (let key of keys) {
156
147
  try {
157
- const pubKey = new node_rsa_1.default();
148
+ const pubKey = new NodeRSA();
158
149
  const keyComponents = {
159
150
  n: Buffer.from(key.n, 'base64'),
160
151
  e: Buffer.from(key.e, 'base64')
161
152
  };
162
153
  pubKey.importKey(keyComponents, 'components-public');
163
- const decoded = jsonwebtoken_1.default.verify(identityToken, pubKey.exportKey('public'), {
154
+ const decoded = jwt.verify(identityToken, pubKey.exportKey('public'), {
164
155
  algorithms: ['RS256'],
165
156
  audience: clientId,
166
157
  issuer: 'https://appleid.apple.com'
@@ -178,4 +169,3 @@ const apple = async (param) => {
178
169
  const payload = await genPayload(identityToken);
179
170
  return payload;
180
171
  };
181
- exports.apple = apple;