-
Notifications
You must be signed in to change notification settings - Fork 14
/
builders.ts
274 lines (241 loc) · 7.33 KB
/
builders.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import Debug from "debug";
import cloneDeep from "lodash.clonedeep";
import slugify from "slugify";
import {
FullItem,
FullItemAllOfFields,
FullItemAllOfSections,
GeneratorRecipe,
ItemUrls,
ItemVault,
} from "../model/models";
import { generateSectionId } from './utils';
const debug = Debug("opconnect:builder");
export interface ItemFieldOptions {
value?: string;
type?: FullItemAllOfFields.TypeEnum;
sectionName?: string;
purpose?: FullItemAllOfFields.PurposeEnum;
label?: string;
generate?: boolean;
recipe?: GeneratorRecipe;
}
export class ItemBuilder {
/**
* Empty Item under construction.
*
* @private
*/
private item: FullItem;
/**
* Hashmap to support get-or-create operations on "sections" when adding fields
*
* @private
*/
private sections: Map<string, FullItemAllOfSections>;
private urls: { [key: string]: any };
public constructor() {
this.reset();
}
/**
* Performs final assembly of the new Item.
*/
public build(): FullItem {
if (!this.item.category) {
throw Error("Item Category is required.");
}
this.item.sections = Array.from(this.sections.values());
this.item.urls = this.urls.hrefs.map((href) =>
this.urls.primaryUrl === href
? ({ primary: true, href } as ItemUrls)
: ({ href } as ItemUrls),
);
const builtItem = cloneDeep(this.item);
debug(
"Successfully built Item (id: %s, vault: %s)",
builtItem.id,
);
this.reset();
return builtItem;
}
/**
* Clears accumulated properties and puts
* ItemBuilder back to a "pristine" state
*/
public reset(): void {
this.item = new FullItem();
this.item.fields = [];
this.item.tags = [];
this.sections = new Map();
this.urls = { primaryUrl: "", hrefs: [] };
}
/**
* @deprecated
* Sets the parent Vault ID for the Item being constructed.
*
* @param {string} vaultId
* @returns {ItemBuilder}
*/
public setVault(vaultId: string): ItemBuilder {
this.item.vault = { id: vaultId } as ItemVault;
return this;
}
/**
* Set Title for the item under construction
*
* @param {string} title
* @returns {ItemBuilder}
*/
public setTitle(title: string): ItemBuilder {
this.item.title = title;
return this;
}
/**
* Append new tag to list of tags
* 1Password does not normalize tag inputs.
*
* @param {string} tag
* @returns {ItemBuilder}
*/
public addTag(tag: string): ItemBuilder {
this.item.tags.push(tag);
return this;
}
/**
* Append new Item Field to the in-flight Item.
*
* @param {ItemFieldOptions} opts
* @returns {ItemBuilder}
*/
public addField(opts: ItemFieldOptions = {}): ItemBuilder {
if (opts.generate && !validRecipe(opts.recipe)) {
throw TypeError(
`Field '${opts.label}' contains an invalid Recipe.`,
);
}
const field: FullItemAllOfFields = {
type: opts.type || FullItemAllOfFields.TypeEnum.String,
purpose: opts.purpose || FullItemAllOfFields.PurposeEnum.Empty,
label: opts.label,
value: opts.value,
generate: opts.generate || false,
recipe: opts.generate && opts.recipe ? generatorRecipeFromConfig(opts.recipe): undefined
};
if (opts.sectionName) {
const { id: sectionId } = this.getOrCreateSection(opts.sectionName);
field.section = { id: sectionId };
}
this.item.fields.push(field);
return this;
}
/**
* Define a new section within the Item.
*
* If a section with the same (normalized) name
* already exists, do nothing.
*
* @param sectionName
* @returns {ItemBuilder}
*/
public addSection(sectionName: string): ItemBuilder {
this.getOrCreateSection(sectionName);
return this;
}
/**
* Toggle `favorite` value on the in-flight Item.
*
* @returns {ItemBuilder}
*/
public toggleFavorite(): ItemBuilder {
this.item.favorite = !this.item.favorite;
return this;
}
/**
* Add a new URL to the Item.
*
* The **last** url marked `primary` will be the primary URL
* when saved to 1Password.
*
* @param url
* @returns {ItemBuilder}
*/
public addUrl(url: ItemUrls): ItemBuilder {
if (url.primary) this.urls.primaryUrl = url.href;
this.urls.hrefs.push(url.href);
return this;
}
/**
* Assign category to the Item under construction.
*
* @param category
* @returns {ItemBuilder}
*/
public setCategory(category: FullItem.CategoryEnum | string): ItemBuilder {
if (Object.values(FullItem.CategoryEnum).indexOf(category) === -1) {
throw TypeError("Item Category is invalid");
}
this.item.category = category as FullItem.CategoryEnum;
return this;
}
/**
* Creates a new Item Section if it does not exist. Otherwise, return the previously-created
* Item Section.
*
* Normalizes sectionName as a slug (utf-8 chars are transformed to ascii).
*
* @param sectionName
* @private
* @return {FullItemAllOfSections}
*/
private getOrCreateSection(sectionName: string): FullItemAllOfSections {
const normalizedName = slugify(sectionName, { lower: true, remove: /[*+~.()'"!:@]/g});
if (this.sections.has(normalizedName)) {
return this.sections.get(normalizedName);
}
// Note about Section IDs: these do NOT have to be cryptographically random.
// Section IDs are only unique within an Item.
const section: FullItemAllOfSections = {
id: generateSectionId(),
label: sectionName,
};
this.sections.set(normalizedName, section);
return section;
}
}
/**
* Creates a well-formed GeneratorRecipe from the provided options.
* Namely, it removes duplicate values from the character set definitions.
* @param {Partial<GeneratorRecipe>} opts
* @return {GeneratorRecipe}
*/
const generatorRecipeFromConfig = (opts: Partial<GeneratorRecipe>): GeneratorRecipe => {
// excluded character setting cannot contain duplicate entries
const excludeCharacters = [...new Set(opts.excludeCharacters)].reduce(
(acc, curr) => acc + curr, ""
)
return {
...opts,
characterSets: [...new Set(opts.characterSets)],
excludeCharacters
}
}
/**
* Evaluate Recipe parameters against allowed values.
*
* @param {GeneratorRecipe} recipe
* @returns {boolean}
*/
const validRecipe = (recipe: GeneratorRecipe): boolean => {
if (!recipe.characterSets || !recipe.characterSets.length) return true;
const allowedCharactersSets = Object.values(
GeneratorRecipe.CharacterSetsEnum,
);
// User provided more character sets than are defined
if (recipe.characterSets.length > allowedCharactersSets.length) return false;
for (const cs of recipe.characterSets) {
if (allowedCharactersSets.indexOf(cs) === -1) {
return false;
}
}
return true;
};