@hello.nrfcloud.com/nrfcloud-api-helpers 6.0.466 → 6.0.467

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 (41) hide show
  1. package/npm/src/api/DeviceShadow.js +32 -0
  2. package/npm/src/api/FetchError.js +9 -0
  3. package/npm/src/api/bulkOps.d.ts +5 -3
  4. package/npm/src/api/bulkOps.js +22 -0
  5. package/npm/src/api/cancelFOTAJob.d.ts +1 -1
  6. package/npm/src/api/cancelFOTAJob.js +15 -0
  7. package/npm/src/api/createAccountDevice.d.ts +4 -10
  8. package/npm/src/api/createAccountDevice.js +25 -0
  9. package/npm/src/api/createFOTAJob.d.ts +4 -3
  10. package/npm/src/api/createFOTAJob.js +32 -0
  11. package/npm/src/api/deleteAccountDevice.js +9 -0
  12. package/npm/src/api/devices.d.ts +47 -27
  13. package/npm/src/api/devices.js +98 -0
  14. package/npm/src/api/export.js +18 -0
  15. package/npm/src/api/getAccountInfo.d.ts +9 -2
  16. package/npm/src/api/getAccountInfo.js +20 -0
  17. package/npm/src/api/getCurrentMonthlyCosts.d.ts +1 -1
  18. package/npm/src/api/getCurrentMonthlyCosts.js +22 -0
  19. package/npm/src/api/getDeviceShadow.d.ts +21 -18
  20. package/npm/src/api/getDeviceShadow.js +42 -0
  21. package/npm/src/api/getFOTABundles.d.ts +11 -3
  22. package/npm/src/api/getFOTABundles.js +101 -0
  23. package/npm/src/api/getFOTAJob.d.ts +23 -3
  24. package/npm/src/api/getFOTAJob.js +114 -0
  25. package/npm/src/api/getLocationHistory.d.ts +24 -5
  26. package/npm/src/api/getLocationHistory.js +118 -0
  27. package/npm/src/api/groundFix.d.ts +8 -4
  28. package/npm/src/api/groundFix.js +38 -0
  29. package/npm/src/api/serviceToken.d.ts +2 -2
  30. package/npm/src/api/serviceToken.js +20 -0
  31. package/npm/src/api/slashless.js +1 -0
  32. package/npm/src/api/validatedFetch.d.ts +6 -4
  33. package/npm/src/api/validatedFetch.js +58 -0
  34. package/npm/src/settings/export.js +5 -0
  35. package/npm/src/settings/getAllAccounts.js +9 -0
  36. package/npm/src/settings/getAllAccountsSettings.js +13 -0
  37. package/npm/src/settings/groupByAccount.js +16 -0
  38. package/npm/src/settings/scope.js +6 -0
  39. package/npm/src/settings/settings.d.ts +7 -13
  40. package/npm/src/settings/settings.js +83 -0
  41. package/package.json +2 -2
@@ -0,0 +1,101 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { FwType } from './devices.js';
3
+ import { validatedFetch } from './validatedFetch.js';
4
+ export const FOTABundle = Type.Object({
5
+ bundleId: Type.String({
6
+ minLength: 1,
7
+ description: 'The ID of the bundle',
8
+ examples: [
9
+ 'APP*20a4b75a*v1.1.1-debug'
10
+ ]
11
+ }),
12
+ lastModified: Type.Optional(Type.String({
13
+ title: 'Timestamp',
14
+ description: 'ISO-8601 date-time string',
15
+ examples: [
16
+ '2019-08-24T14:15:22Z'
17
+ ]
18
+ })),
19
+ size: Type.Number({
20
+ minimum: 0,
21
+ description: 'Size of the bundle in bytes',
22
+ examples: [
23
+ 418565
24
+ ]
25
+ }),
26
+ version: Type.String({
27
+ minLength: 1,
28
+ examples: [
29
+ 'v1.1.1-debug'
30
+ ]
31
+ }),
32
+ type: Type.Enum(FwType, {
33
+ title: 'Firmware Type'
34
+ }),
35
+ filenames: Type.Array(Type.String({
36
+ minLength: 1,
37
+ examples: [
38
+ 'hello-nrfcloud-thingy91-debug-v1.1.1-fwupd.bin'
39
+ ]
40
+ }), {
41
+ description: 'The files in the bundle.'
42
+ }),
43
+ name: Type.Optional(Type.String({
44
+ minLength: 1,
45
+ title: 'Name',
46
+ description: 'The name of the bundle',
47
+ examples: [
48
+ 'hello.nrfcloud.com v1.1.1-debug'
49
+ ]
50
+ })),
51
+ description: Type.Optional(Type.String({
52
+ minLength: 1,
53
+ title: 'Description',
54
+ description: 'The description of the bundle',
55
+ examples: [
56
+ 'Firmware Update Image BIN file (thingy91, debug)'
57
+ ]
58
+ }))
59
+ });
60
+ const FirmwaresType = Type.Object({
61
+ items: Type.Array(FOTABundle),
62
+ total: Type.Integer({
63
+ minimum: 0,
64
+ description: 'Reflects the total results returned by the query, which may be less than the total number of items available. If the response contains a pageNextToken value, you can supply the pageNextToken in the next request to get more results. The maximum value of total is the page limit of the request, or ten pages if no page limit is provided.'
65
+ }),
66
+ pageNextToken: Type.Optional(Type.String({
67
+ minLength: 1,
68
+ description: 'Token used to retrieve the next page of items in the list. Present in a response only if the total available results exceeds the specified limit on a page. This token does not change between requests. When supplying as a request parameter, use URL-encoding.'
69
+ }))
70
+ }, {
71
+ title: 'Firmware bundles',
72
+ description: 'Returns the list of firmware bundles. See https://api.nrfcloud.com/v1#tag/Firmware-Bundles/operation/ListFirmware'
73
+ });
74
+ export const getFOTABundles = ({ apiKey, endpoint }, fetchImplementation)=>async ()=>{
75
+ const vf = validatedFetch({
76
+ endpoint,
77
+ apiKey
78
+ }, fetchImplementation);
79
+ return paginateFirmwares(vf);
80
+ };
81
+ const paginateFirmwares = async (vf, bundles = [], pageNextToken = undefined)=>{
82
+ const query = new URLSearchParams({
83
+ pageLimit: '100'
84
+ });
85
+ if (pageNextToken !== undefined) query.set('pageNextToken', pageNextToken);
86
+ const maybeBundles = await vf({
87
+ resource: `firmwares`,
88
+ query
89
+ }, FirmwaresType);
90
+ if ('error' in maybeBundles) return maybeBundles;
91
+ if (maybeBundles.result.pageNextToken !== undefined) return paginateFirmwares(vf, [
92
+ ...bundles,
93
+ ...maybeBundles.result.items
94
+ ], maybeBundles.result.pageNextToken);
95
+ return {
96
+ bundles: [
97
+ ...bundles,
98
+ ...maybeBundles.result.items
99
+ ]
100
+ };
101
+ };
@@ -1,4 +1,3 @@
1
- import { type Static } from '@sinclair/typebox';
2
1
  import { FwType } from './devices.ts';
3
2
  import type { FetchError } from './FetchError.ts';
4
3
  import type { ValidationError } from './validatedFetch.ts';
@@ -40,10 +39,31 @@ export declare const FOTAJobType: import("@sinclair/typebox").TObject<{
40
39
  export declare const getFOTAJob: ({ apiKey, endpoint, }: {
41
40
  apiKey: string;
42
41
  endpoint: URL;
43
- }, fetchImplementation?: typeof fetch) => ({ jobId, }: {
42
+ }, fetchImplementation?: typeof fetch | undefined) => ({ jobId, }: {
44
43
  jobId: string;
45
44
  }) => Promise<{
46
45
  error: FetchError | ValidationError;
47
46
  } | {
48
- result: Static<typeof FOTAJobType>;
47
+ result: {
48
+ jobId: string;
49
+ status: FOTAJobStatus;
50
+ statusDetail?: string | undefined;
51
+ name?: string | undefined;
52
+ description?: string | undefined;
53
+ createdAt: string;
54
+ lastUpdatedAt?: string | undefined;
55
+ completedAt?: string | undefined;
56
+ firmware?: {
57
+ bundleId: string;
58
+ fileSize: number;
59
+ firmwareType: FwType;
60
+ host: string;
61
+ uris: string[];
62
+ version: string;
63
+ } | undefined;
64
+ target?: {
65
+ deviceIds: string[];
66
+ tags: string[];
67
+ } | undefined;
68
+ };
49
69
  }>;
@@ -0,0 +1,114 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { FwType } from './devices.js';
3
+ import { validatedFetch } from './validatedFetch.js';
4
+ export var FOTAJobStatus = /*#__PURE__*/ function(FOTAJobStatus) {
5
+ FOTAJobStatus["CREATED"] = "CREATED";
6
+ FOTAJobStatus["IN_PROGRESS"] = "IN_PROGRESS";
7
+ FOTAJobStatus["CANCELLED"] = "CANCELLED";
8
+ FOTAJobStatus["DELETION_IN_PROGRESS"] = "DELETION_IN_PROGRESS";
9
+ FOTAJobStatus["COMPLETED"] = "COMPLETED";
10
+ FOTAJobStatus["QUEUED"] = "QUEUED";
11
+ FOTAJobStatus["FAILED"] = "FAILED";
12
+ FOTAJobStatus["SUCCEEDED"] = "SUCCEEDED";
13
+ FOTAJobStatus["TIMED_OUT"] = "TIMED_OUT";
14
+ FOTAJobStatus["REJECTED"] = "REJECTED";
15
+ FOTAJobStatus["DOWNLOADING"] = "DOWNLOADING";
16
+ return FOTAJobStatus;
17
+ }({});
18
+ const ts = Type.String({
19
+ title: 'Timestamp',
20
+ description: 'ISO-8601 date-time string',
21
+ examples: [
22
+ '2019-08-24T14:15:22Z'
23
+ ]
24
+ });
25
+ export const FOTAJobType = Type.Object({
26
+ jobId: Type.String({
27
+ minLength: 1,
28
+ title: 'ID',
29
+ description: 'Universally unique identifier',
30
+ examples: [
31
+ 'bc631093-7f7c-4c1b-aa63-a68c759bcd5c'
32
+ ]
33
+ }),
34
+ status: Type.Enum(FOTAJobStatus, {
35
+ title: 'Status',
36
+ description: 'Current status of the job'
37
+ }),
38
+ statusDetail: Type.Optional(Type.String({
39
+ minLength: 0
40
+ })),
41
+ name: Type.Optional(Type.String({
42
+ minLength: 1
43
+ })),
44
+ description: Type.Optional(Type.String({
45
+ minLength: 1
46
+ })),
47
+ createdAt: ts,
48
+ lastUpdatedAt: Type.Optional(ts),
49
+ completedAt: Type.Optional(ts),
50
+ firmware: Type.Optional(Type.Object({
51
+ bundleId: Type.String({
52
+ minLength: 1,
53
+ examples: [
54
+ 'APP*439ddbc7*v2.0.0'
55
+ ]
56
+ }),
57
+ fileSize: Type.Number({
58
+ minimum: 1,
59
+ examples: [
60
+ 385068
61
+ ]
62
+ }),
63
+ firmwareType: Type.Enum(FwType, {
64
+ title: 'Firmware Type'
65
+ }),
66
+ host: Type.String({
67
+ minLength: 1,
68
+ examples: [
69
+ 'firmware.nrfcloud.com'
70
+ ]
71
+ }),
72
+ uris: Type.Array(Type.String({
73
+ minLength: 1,
74
+ examples: [
75
+ 'bbfe6b73-a46a-43ad-94bd-8e4b4a7847ce/APP*439ddbc7*v2.0.0/hello-nrfcloud-thingy91-v2.0.0-fwupd.bin'
76
+ ]
77
+ })),
78
+ version: Type.String({
79
+ minLength: 1,
80
+ examples: [
81
+ 'v2.0.0'
82
+ ]
83
+ })
84
+ })),
85
+ target: Type.Optional(Type.Object({
86
+ deviceIds: Type.Array(Type.String({
87
+ minLength: 1,
88
+ title: 'Device ID',
89
+ examples: [
90
+ 'oob-358299840021360'
91
+ ]
92
+ })),
93
+ tags: Type.Array(Type.String({
94
+ minLength: 1,
95
+ title: 'Tag',
96
+ examples: [
97
+ 'nrf9160'
98
+ ]
99
+ }))
100
+ }))
101
+ }, {
102
+ title: 'FOTA Job',
103
+ description: 'See https://api.nrfcloud.com/#tag/FOTA-Jobs/operation/FetchFOTAJob'
104
+ });
105
+ export const getFOTAJob = ({ apiKey, endpoint }, fetchImplementation)=>async ({ jobId })=>{
106
+ const maybeJob = await validatedFetch({
107
+ endpoint,
108
+ apiKey
109
+ }, fetchImplementation)({
110
+ resource: `fota-jobs/${jobId}`
111
+ }, FOTAJobType);
112
+ if ('error' in maybeJob) return maybeJob;
113
+ return maybeJob;
114
+ };
@@ -34,14 +34,33 @@ export type LocationHistory = Static<typeof LocationHistoryType>;
34
34
  export declare const getLocationHistory: ({ apiKey, endpoint, }: {
35
35
  apiKey: string;
36
36
  endpoint: URL;
37
- }, fetchImplementation?: typeof fetch) => ({ deviceId, pageNextToken, start, end, }: {
37
+ }, fetchImplementation?: typeof fetch | undefined) => ({ deviceId, pageNextToken, start, end, }: {
38
38
  deviceId: string;
39
- pageNextToken?: string;
40
- start?: Date;
41
- end?: Date;
39
+ pageNextToken?: string | undefined;
40
+ start?: Date | undefined;
41
+ end?: Date | undefined;
42
42
  }) => Promise<{
43
43
  error: FetchError | ValidationError;
44
44
  } | {
45
- result: Static<typeof LocationHistoryType>;
45
+ result: {
46
+ items: {
47
+ id: string;
48
+ deviceId: string;
49
+ serviceType: LocationHistoryServiceType;
50
+ insertedAt: string;
51
+ lat: string;
52
+ lon: string;
53
+ meta: {
54
+ [x: string]: any;
55
+ };
56
+ uncertainty: string;
57
+ anchors?: {
58
+ macAddress: string;
59
+ name?: string | undefined;
60
+ }[] | undefined;
61
+ }[];
62
+ total: number;
63
+ pageNextToken?: string | undefined;
64
+ };
46
65
  }>;
47
66
  export {};
@@ -0,0 +1,118 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { validatedFetch } from './validatedFetch.js';
3
+ export var LocationHistoryServiceType = /*#__PURE__*/ function(LocationHistoryServiceType) {
4
+ LocationHistoryServiceType["ANCHOR"] = "ANCHOR";
5
+ LocationHistoryServiceType["GNSS"] = "GNSS";
6
+ LocationHistoryServiceType["GPS"] = "GPS";
7
+ LocationHistoryServiceType["MCELL"] = "MCELL";
8
+ LocationHistoryServiceType["MCELL_EVAL"] = "MCELL_EVAL";
9
+ LocationHistoryServiceType["SCELL"] = "SCELL";
10
+ LocationHistoryServiceType["SCELL_EVAL"] = "SCELL_EVAL";
11
+ LocationHistoryServiceType["WIFI"] = "WIFI";
12
+ LocationHistoryServiceType["WIFI_EVAL"] = "WIFI_EVAL";
13
+ return LocationHistoryServiceType;
14
+ }({});
15
+ const LocationHistoryType = Type.Object({
16
+ items: Type.Array(Type.Object({
17
+ id: Type.String({
18
+ minLength: 1,
19
+ title: 'ID',
20
+ description: 'Universally unique identifier',
21
+ examples: [
22
+ 'bc631093-7f7c-4c1b-aa63-a68c759bcd5c'
23
+ ]
24
+ }),
25
+ deviceId: Type.String({
26
+ minLength: 1,
27
+ title: 'This is the canonical device id used in the device certificate, and as the MQTT client id.',
28
+ examples: [
29
+ 'nrf-1234567890123456789000'
30
+ ]
31
+ }),
32
+ serviceType: Type.Enum(LocationHistoryServiceType, {
33
+ title: 'Tracker Service Type',
34
+ description: 'This is the service used to obtain the location of a device. The "_EVAL" suffix means the location was obtained using an evaluation token. GNSS location is derived on the device and reported back to the cloud. "GPS" type has been deprecated, but will still return for older records.',
35
+ examples: [
36
+ 'location'
37
+ ]
38
+ }),
39
+ insertedAt: Type.String({
40
+ title: 'Insertion Time',
41
+ description: 'HTML-encoded ISO-8601 date-time string denoting the start or end of a date range. If the string includes only a date, the time is the beginning of the day (00:00:00).',
42
+ examples: [
43
+ '2021-08-31T20:00:00Z'
44
+ ]
45
+ }),
46
+ lat: Type.String({
47
+ minLength: 1,
48
+ examples: [
49
+ '63.41999531'
50
+ ],
51
+ description: 'Latitude in degrees'
52
+ }),
53
+ lon: Type.String({
54
+ minLength: 1,
55
+ examples: [
56
+ '-122.688408'
57
+ ],
58
+ description: 'Longitude in degrees'
59
+ }),
60
+ meta: Type.Record(Type.String({
61
+ minLength: 1
62
+ }), Type.Any(), {
63
+ title: 'GNSS metatdata',
64
+ description: 'Metadata sent from device when reporting GNSS location in PVT format. Can include other non-gnss related key/value pairs for easy retrieval later. Only populated for GNSS PVT formatted fixes, empty object otherwise.'
65
+ }),
66
+ uncertainty: Type.RegExp(/^[0-9.]+$/, {
67
+ title: 'Uncertainty',
68
+ description: 'Radius of the uncertainty circle around the location in meters. Also known as Horizontal Positioning Error (HPE).',
69
+ examples: [
70
+ '2420',
71
+ '13.012'
72
+ ]
73
+ }),
74
+ anchors: Type.Optional(Type.Array(Type.Object({
75
+ macAddress: Type.RegExp(/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i, {
76
+ title: 'Mac Address',
77
+ description: 'String comprised of 6 hexadecimal pairs, separated by colons or dashes. When used in a positioning request, it must be universally assigned. See this help page for details.',
78
+ examples: [
79
+ 'FE:1E:41:2D:9E:53'
80
+ ]
81
+ }),
82
+ name: Type.Optional(Type.RegExp(/^[a-z0-9_ -]{1,32}$/i, {
83
+ title: 'Name',
84
+ description: 'Limit 32 characters. Only numbers, letters, underscores, dashes, and spaces allowed. All other characters will be removed.',
85
+ examples: [
86
+ 'anchor-1'
87
+ ]
88
+ }))
89
+ })))
90
+ })),
91
+ total: Type.Number({
92
+ minimum: 0
93
+ }),
94
+ pageNextToken: Type.Optional(Type.String({
95
+ minLength: 1
96
+ }))
97
+ }, {
98
+ title: 'Location History',
99
+ description: 'See https://api.nrfcloud.com/v1#tag/Location-History/operation/GetLocationHistory'
100
+ });
101
+ export const getLocationHistory = ({ apiKey, endpoint }, fetchImplementation)=>async ({ deviceId, pageNextToken, start, end })=>{
102
+ const query = new URLSearchParams({
103
+ pageLimit: '100',
104
+ deviceId
105
+ });
106
+ if (start !== undefined) query.set('start', start.toISOString());
107
+ if (end !== undefined) query.set('end', end.toISOString());
108
+ if (pageNextToken !== undefined) query.set('pageNextToken', pageNextToken);
109
+ const maybeHistory = await validatedFetch({
110
+ endpoint,
111
+ apiKey
112
+ }, fetchImplementation)({
113
+ resource: 'location/history',
114
+ query
115
+ }, LocationHistoryType);
116
+ if ('error' in maybeHistory) return maybeHistory;
117
+ return maybeHistory;
118
+ };
@@ -1,4 +1,3 @@
1
- import { type Static } from '@sinclair/typebox';
2
1
  import type { FetchError } from './FetchError.ts';
3
2
  import { type ValidationError } from './validatedFetch.ts';
4
3
  export declare const lat: import("@sinclair/typebox").TNumber;
@@ -16,14 +15,19 @@ export declare const GroundFixType: import("@sinclair/typebox").TObject<{
16
15
  export declare const groundFix: ({ apiKey, endpoint, }: {
17
16
  apiKey: string;
18
17
  endpoint: URL;
19
- }, fetchImplementation?: typeof fetch) => (cell: {
18
+ }, fetchImplementation?: typeof fetch | undefined) => (cell: {
20
19
  mcc: number;
21
20
  mnc: string;
22
21
  eci: number;
23
22
  tac: number;
24
- rsrp?: number;
23
+ rsrp?: number | undefined;
25
24
  }) => Promise<{
26
25
  error: FetchError | ValidationError;
27
26
  } | {
28
- result: Static<typeof GroundFixType>;
27
+ result: {
28
+ lat: number;
29
+ lon: number;
30
+ uncertainty: number;
31
+ fulfilledWith: "SCELL";
32
+ };
29
33
  }>;
@@ -0,0 +1,38 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { JSONPayload, validatedFetch } from './validatedFetch.js';
3
+ export const lat = Type.Number({
4
+ minimum: -90,
5
+ maximum: 90,
6
+ description: 'Latitude in degrees'
7
+ });
8
+ export const lng = Type.Number({
9
+ minimum: -180,
10
+ maximum: 180,
11
+ description: 'Longitude in degrees'
12
+ });
13
+ export const accuracy = Type.Number({
14
+ minimum: 0,
15
+ description: 'HPE (horizontal positioning error) in meters'
16
+ });
17
+ /**
18
+ * @link https://api.nrfcloud.com/v1/#tag/Ground-Fix
19
+ */ export const GroundFixType = Type.Object({
20
+ lat,
21
+ lon: lng,
22
+ uncertainty: accuracy,
23
+ fulfilledWith: Type.Literal('SCELL')
24
+ });
25
+ export const groundFix = ({ apiKey, endpoint }, fetchImplementation)=>async (cell)=>{
26
+ const vf = validatedFetch({
27
+ endpoint,
28
+ apiKey
29
+ }, fetchImplementation);
30
+ return vf({
31
+ resource: 'location/ground-fix',
32
+ payload: JSONPayload({
33
+ lte: [
34
+ cell
35
+ ]
36
+ })
37
+ }, GroundFixType);
38
+ };
@@ -9,8 +9,8 @@ export declare const ServiceToken: import("@sinclair/typebox").TObject<{
9
9
  export declare const serviceToken: ({ apiKey, endpoint, }: {
10
10
  apiKey: string;
11
11
  endpoint: URL;
12
- }, fetchImplementation?: typeof fetch) => (() => Promise<{
12
+ }, fetchImplementation?: typeof fetch | undefined) => () => Promise<{
13
13
  error: FetchError | ValidationError;
14
14
  } | {
15
15
  token: string;
16
- }>);
16
+ }>;
@@ -0,0 +1,20 @@
1
+ import { Type } from '@sinclair/typebox';
2
+ import { validatedFetch } from './validatedFetch.js';
3
+ /**
4
+ * @link https://api.nrfcloud.com/v1/#tag/Account/operation/GetServiceToken
5
+ */ export const ServiceToken = Type.Object({
6
+ token: Type.String()
7
+ });
8
+ export const serviceToken = ({ apiKey, endpoint }, fetchImplementation)=>async ()=>{
9
+ const vf = validatedFetch({
10
+ endpoint,
11
+ apiKey
12
+ }, fetchImplementation);
13
+ const maybeResult = await vf({
14
+ resource: 'account/service-token'
15
+ }, ServiceToken);
16
+ if ('error' in maybeResult) {
17
+ return maybeResult;
18
+ }
19
+ return maybeResult.result;
20
+ };
@@ -0,0 +1 @@
1
+ export const slashless = (url)=>url.toString().replace(/\/$/, '');
@@ -1,4 +1,4 @@
1
- import { type Static, type TSchema } from '@sinclair/typebox';
1
+ import { type TSchema } from '@sinclair/typebox';
2
2
  import type { ValueError } from '@sinclair/typebox/compiler';
3
3
  import type { FetchError } from './FetchError.ts';
4
4
  export declare class ValidationError extends Error {
@@ -9,7 +9,7 @@ export declare class ValidationError extends Error {
9
9
  export declare const validatedFetch: ({ endpoint, apiKey }: {
10
10
  apiKey: string;
11
11
  endpoint: URL;
12
- }, fetchImplementation?: typeof fetch) => <Schema extends TSchema>(params: ({
12
+ }, fetchImplementation?: typeof fetch | undefined) => <Schema extends TSchema>(params: ({
13
13
  resource: string;
14
14
  } | {
15
15
  resource: string;
@@ -18,11 +18,13 @@ export declare const validatedFetch: ({ endpoint, apiKey }: {
18
18
  resource: string;
19
19
  method: string;
20
20
  }) & {
21
- query?: URLSearchParams;
21
+ query?: URLSearchParams | undefined;
22
22
  }, schema: Schema) => Promise<{
23
23
  error: FetchError | ValidationError;
24
24
  } | {
25
- result: Static<Schema>;
25
+ result: (Schema & {
26
+ params: [];
27
+ })["static"];
26
28
  }>;
27
29
  type Payload = {
28
30
  /** The content-type of body */
@@ -0,0 +1,58 @@
1
+ import { validateWithTypeBox } from '@hello.nrfcloud.com/proto';
2
+ import { toFetchError } from './FetchError.js';
3
+ import { slashless } from './slashless.js';
4
+ export class ValidationError extends Error {
5
+ errors;
6
+ isValidationError = true;
7
+ constructor(errors){
8
+ super(`Validation errors`);
9
+ this.name = 'ValidationError';
10
+ this.errors = errors;
11
+ }
12
+ }
13
+ const validate = (SchemaObject, data)=>{
14
+ const maybeData = validateWithTypeBox(SchemaObject)(data);
15
+ if ('errors' in maybeData) {
16
+ console.error('Validation failed', {
17
+ error: maybeData.errors
18
+ });
19
+ throw new ValidationError(maybeData.errors);
20
+ }
21
+ return maybeData.value;
22
+ };
23
+ const fetchData = (fetchImplementation)=>async (...args)=>{
24
+ const response = await (fetchImplementation ?? fetch)(...args);
25
+ if (!response.ok) throw await toFetchError(response);
26
+ if (response.headers?.get('content-length') === '0') return undefined;
27
+ return response.json();
28
+ };
29
+ export const validatedFetch = ({ endpoint, apiKey }, fetchImplementation)=>async (params, schema)=>{
30
+ const { resource, query } = params;
31
+ const args = {
32
+ headers: headers(apiKey)
33
+ };
34
+ if ('payload' in params) {
35
+ const payload = params.payload;
36
+ args.method = 'POST';
37
+ args.body = payload.body;
38
+ args.headers = {
39
+ ...args.headers ?? {},
40
+ ['Content-Type']: payload.type
41
+ };
42
+ } else if ('method' in params) {
43
+ args.method = params.method;
44
+ }
45
+ return fetchData(fetchImplementation)(`${slashless(endpoint)}/v1/${resource}${query !== undefined ? `?${query.toString()}` : ''}`, args).then((res)=>({
46
+ result: validate(schema, res)
47
+ })).catch((error)=>({
48
+ error
49
+ }));
50
+ };
51
+ const headers = (apiKey)=>({
52
+ Authorization: `Bearer ${apiKey}`,
53
+ Accept: 'application/json; charset=utf-8'
54
+ });
55
+ export const JSONPayload = (payload)=>({
56
+ type: 'application/json',
57
+ body: JSON.stringify(payload)
58
+ });
@@ -0,0 +1,5 @@
1
+ export * from './getAllAccounts.js';
2
+ export * from './getAllAccountsSettings.js';
3
+ export * from './groupByAccount.js';
4
+ export * from './scope.js';
5
+ export * from './settings.js';
@@ -0,0 +1,9 @@
1
+ import { get } from '@bifravst/aws-ssm-settings-helpers';
2
+ import { NRFCLOUD_ACCOUNT_SCOPE } from './scope.js';
3
+ export const getAllAccounts = async ({ ssm, stackName })=>[
4
+ ...getAccountsFromAllSettings(await get(ssm)({
5
+ stackName,
6
+ scope: NRFCLOUD_ACCOUNT_SCOPE
7
+ })())
8
+ ];
9
+ export const getAccountsFromAllSettings = (settings)=>new Set(Object.keys(settings).map((key)=>key.split('/')[0]));
@@ -0,0 +1,13 @@
1
+ import { get } from '@bifravst/aws-ssm-settings-helpers';
2
+ import { groupByAccount } from './groupByAccount.js';
3
+ import { NRFCLOUD_ACCOUNT_SCOPE } from './scope.js';
4
+ import { validateSettings } from './settings.js';
5
+ /**
6
+ * Returns settings for all accounts
7
+ */ export const getAllAccountsSettings = async ({ ssm, stackName })=>Object.entries(groupByAccount(await get(ssm)({
8
+ stackName,
9
+ scope: NRFCLOUD_ACCOUNT_SCOPE
10
+ })())).reduce((allSettings, [account, settings])=>({
11
+ ...allSettings,
12
+ [account]: validateSettings(settings)
13
+ }), {});
@@ -0,0 +1,16 @@
1
+ import { getAccountsFromAllSettings } from './getAllAccounts.js';
2
+ export const groupByAccount = (allSettings)=>{
3
+ const accounts = getAccountsFromAllSettings(allSettings);
4
+ return [
5
+ ...accounts
6
+ ].reduce((allAccountSettings, account)=>({
7
+ ...allAccountSettings,
8
+ [account]: Object.entries(allSettings).filter(([k])=>k.startsWith(`${account}/`)).map(([k, v])=>[
9
+ k.replace(new RegExp(`^${account}/`), ''),
10
+ v
11
+ ]).reduce((s, [k, v])=>({
12
+ ...s,
13
+ [k]: v
14
+ }), {})
15
+ }), {});
16
+ };
@@ -0,0 +1,6 @@
1
+ export const NRFCLOUD_ACCOUNT_SCOPE = 'thirdParty';
2
+ const nameRx = /^[a-zA-Z0-9_.-]+$/;
3
+ export const nrfCloudAccount = (account)=>{
4
+ if (!nameRx.test(account)) throw new Error(`Invalid account name: ${account}`);
5
+ return account;
6
+ };