ofsc-utility 1.0.13 → 1.0.15

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.
@@ -1,43 +1,3394 @@
1
- Object.defineProperty(exports, "__esModule", { value: true });
2
- exports.downloadAllEventsOfDayCSV = exports.downloadAllEventsOfDay = exports.getActivityCustomerInventories = exports.createActivityCustomerInventories = exports.getAllActivities = exports.getActivitybyId = exports.updateCreateInventoryType = exports.getInventoryTypesDetail = exports.downloadAllInventoryTypesCSV = exports.generateUsersCollaborationCSV = exports.downloadAllUsersCSV = exports.downloadAllResourcesCSV = exports.downloadWorkZoneCSV = exports.getOAuthToken = exports.generateAllOnHandInventoryOfAllResourcesCSV = exports.WorkZone = exports.Utilities = exports.User = exports.Resource = exports.OauthTokenService = exports.InventoryType = exports.Inventory = exports.Events = exports.ActivityInventories = exports.Activity = void 0;
3
- const tslib_1 = require("tslib");
1
+ import * as fs from 'fs';
2
+ import fs__default from 'fs';
3
+ import path from 'path';
4
+
5
+ async function getOAuthToken(clientId, clientSecret, instanceUrl) {
6
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/oauthTokenService/v2/token`;
7
+ const credentials = btoa(`${clientId}@${instanceUrl}:${clientSecret}`);
8
+ const headers = {
9
+ 'Content-Type': 'application/x-www-form-urlencoded',
10
+ 'Authorization': `Basic ${credentials}`
11
+ };
12
+ const body = new URLSearchParams({
13
+ 'grant_type': 'client_credentials'
14
+ });
15
+ try {
16
+ const response = await fetch(url, {
17
+ method: 'POST',
18
+ headers: headers,
19
+ body: body
20
+ });
21
+ if (!response.ok) {
22
+ throw new Error(`HTTP error! status: ${response.status}`);
23
+ }
24
+ const data = await response.json();
25
+ return data.access_token;
26
+ }
27
+ catch (error) {
28
+ console.error('Error fetching OAuth token:', error);
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ var index$9 = /*#__PURE__*/Object.freeze({
34
+ __proto__: null,
35
+ getOAuthToken: getOAuthToken
36
+ });
37
+
38
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
39
+
40
+ function getDefaultExportFromCjs (x) {
41
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
42
+ }
43
+
44
+ var domParser = {};
45
+
46
+ var entities = {};
47
+
48
+ var hasRequiredEntities;
49
+
50
+ function requireEntities () {
51
+ if (hasRequiredEntities) return entities;
52
+ hasRequiredEntities = 1;
53
+ entities.entityMap = {
54
+ lt: '<',
55
+ gt: '>',
56
+ amp: '&',
57
+ quot: '"',
58
+ apos: "'",
59
+ Agrave: "À",
60
+ Aacute: "Á",
61
+ Acirc: "Â",
62
+ Atilde: "Ã",
63
+ Auml: "Ä",
64
+ Aring: "Å",
65
+ AElig: "Æ",
66
+ Ccedil: "Ç",
67
+ Egrave: "È",
68
+ Eacute: "É",
69
+ Ecirc: "Ê",
70
+ Euml: "Ë",
71
+ Igrave: "Ì",
72
+ Iacute: "Í",
73
+ Icirc: "Î",
74
+ Iuml: "Ï",
75
+ ETH: "Ð",
76
+ Ntilde: "Ñ",
77
+ Ograve: "Ò",
78
+ Oacute: "Ó",
79
+ Ocirc: "Ô",
80
+ Otilde: "Õ",
81
+ Ouml: "Ö",
82
+ Oslash: "Ø",
83
+ Ugrave: "Ù",
84
+ Uacute: "Ú",
85
+ Ucirc: "Û",
86
+ Uuml: "Ü",
87
+ Yacute: "Ý",
88
+ THORN: "Þ",
89
+ szlig: "ß",
90
+ agrave: "à",
91
+ aacute: "á",
92
+ acirc: "â",
93
+ atilde: "ã",
94
+ auml: "ä",
95
+ aring: "å",
96
+ aelig: "æ",
97
+ ccedil: "ç",
98
+ egrave: "è",
99
+ eacute: "é",
100
+ ecirc: "ê",
101
+ euml: "ë",
102
+ igrave: "ì",
103
+ iacute: "í",
104
+ icirc: "î",
105
+ iuml: "ï",
106
+ eth: "ð",
107
+ ntilde: "ñ",
108
+ ograve: "ò",
109
+ oacute: "ó",
110
+ ocirc: "ô",
111
+ otilde: "õ",
112
+ ouml: "ö",
113
+ oslash: "ø",
114
+ ugrave: "ù",
115
+ uacute: "ú",
116
+ ucirc: "û",
117
+ uuml: "ü",
118
+ yacute: "ý",
119
+ thorn: "þ",
120
+ yuml: "ÿ",
121
+ nbsp: "\u00a0",
122
+ iexcl: "¡",
123
+ cent: "¢",
124
+ pound: "£",
125
+ curren: "¤",
126
+ yen: "¥",
127
+ brvbar: "¦",
128
+ sect: "§",
129
+ uml: "¨",
130
+ copy: "©",
131
+ ordf: "ª",
132
+ laquo: "«",
133
+ not: "¬",
134
+ shy: "­­",
135
+ reg: "®",
136
+ macr: "¯",
137
+ deg: "°",
138
+ plusmn: "±",
139
+ sup2: "²",
140
+ sup3: "³",
141
+ acute: "´",
142
+ micro: "µ",
143
+ para: "¶",
144
+ middot: "·",
145
+ cedil: "¸",
146
+ sup1: "¹",
147
+ ordm: "º",
148
+ raquo: "»",
149
+ frac14: "¼",
150
+ frac12: "½",
151
+ frac34: "¾",
152
+ iquest: "¿",
153
+ times: "×",
154
+ divide: "÷",
155
+ forall: "∀",
156
+ part: "∂",
157
+ exist: "∃",
158
+ empty: "∅",
159
+ nabla: "∇",
160
+ isin: "∈",
161
+ notin: "∉",
162
+ ni: "∋",
163
+ prod: "∏",
164
+ sum: "∑",
165
+ minus: "−",
166
+ lowast: "∗",
167
+ radic: "√",
168
+ prop: "∝",
169
+ infin: "∞",
170
+ ang: "∠",
171
+ and: "∧",
172
+ or: "∨",
173
+ cap: "∩",
174
+ cup: "∪",
175
+ 'int': "∫",
176
+ there4: "∴",
177
+ sim: "∼",
178
+ cong: "≅",
179
+ asymp: "≈",
180
+ ne: "≠",
181
+ equiv: "≡",
182
+ le: "≤",
183
+ ge: "≥",
184
+ sub: "⊂",
185
+ sup: "⊃",
186
+ nsub: "⊄",
187
+ sube: "⊆",
188
+ supe: "⊇",
189
+ oplus: "⊕",
190
+ otimes: "⊗",
191
+ perp: "⊥",
192
+ sdot: "⋅",
193
+ Alpha: "Α",
194
+ Beta: "Β",
195
+ Gamma: "Γ",
196
+ Delta: "Δ",
197
+ Epsilon: "Ε",
198
+ Zeta: "Ζ",
199
+ Eta: "Η",
200
+ Theta: "Θ",
201
+ Iota: "Ι",
202
+ Kappa: "Κ",
203
+ Lambda: "Λ",
204
+ Mu: "Μ",
205
+ Nu: "Ν",
206
+ Xi: "Ξ",
207
+ Omicron: "Ο",
208
+ Pi: "Π",
209
+ Rho: "Ρ",
210
+ Sigma: "Σ",
211
+ Tau: "Τ",
212
+ Upsilon: "Υ",
213
+ Phi: "Φ",
214
+ Chi: "Χ",
215
+ Psi: "Ψ",
216
+ Omega: "Ω",
217
+ alpha: "α",
218
+ beta: "β",
219
+ gamma: "γ",
220
+ delta: "δ",
221
+ epsilon: "ε",
222
+ zeta: "ζ",
223
+ eta: "η",
224
+ theta: "θ",
225
+ iota: "ι",
226
+ kappa: "κ",
227
+ lambda: "λ",
228
+ mu: "μ",
229
+ nu: "ν",
230
+ xi: "ξ",
231
+ omicron: "ο",
232
+ pi: "π",
233
+ rho: "ρ",
234
+ sigmaf: "ς",
235
+ sigma: "σ",
236
+ tau: "τ",
237
+ upsilon: "υ",
238
+ phi: "φ",
239
+ chi: "χ",
240
+ psi: "ψ",
241
+ omega: "ω",
242
+ thetasym: "ϑ",
243
+ upsih: "ϒ",
244
+ piv: "ϖ",
245
+ OElig: "Œ",
246
+ oelig: "œ",
247
+ Scaron: "Š",
248
+ scaron: "š",
249
+ Yuml: "Ÿ",
250
+ fnof: "ƒ",
251
+ circ: "ˆ",
252
+ tilde: "˜",
253
+ ensp: " ",
254
+ emsp: " ",
255
+ thinsp: " ",
256
+ zwnj: "‌",
257
+ zwj: "‍",
258
+ lrm: "‎",
259
+ rlm: "‏",
260
+ ndash: "–",
261
+ mdash: "—",
262
+ lsquo: "‘",
263
+ rsquo: "’",
264
+ sbquo: "‚",
265
+ ldquo: "“",
266
+ rdquo: "”",
267
+ bdquo: "„",
268
+ dagger: "†",
269
+ Dagger: "‡",
270
+ bull: "•",
271
+ hellip: "…",
272
+ permil: "‰",
273
+ prime: "′",
274
+ Prime: "″",
275
+ lsaquo: "‹",
276
+ rsaquo: "›",
277
+ oline: "‾",
278
+ euro: "€",
279
+ trade: "™",
280
+ larr: "←",
281
+ uarr: "↑",
282
+ rarr: "→",
283
+ darr: "↓",
284
+ harr: "↔",
285
+ crarr: "↵",
286
+ lceil: "⌈",
287
+ rceil: "⌉",
288
+ lfloor: "⌊",
289
+ rfloor: "⌋",
290
+ loz: "◊",
291
+ spades: "♠",
292
+ clubs: "♣",
293
+ hearts: "♥",
294
+ diams: "♦"
295
+ };
296
+ return entities;
297
+ }
298
+
299
+ var sax = {};
300
+
301
+ var hasRequiredSax;
302
+
303
+ function requireSax () {
304
+ if (hasRequiredSax) return sax;
305
+ hasRequiredSax = 1;
306
+ //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
307
+ //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
308
+ //[5] Name ::= NameStartChar (NameChar)*
309
+ var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;//\u10000-\uEFFFF
310
+ var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
311
+ var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
312
+ //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
313
+ //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
314
+
315
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
316
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
317
+ var S_TAG = 0;//tag name offerring
318
+ var S_ATTR = 1;//attr name offerring
319
+ var S_ATTR_SPACE=2;//attr name end and space offer
320
+ var S_EQ = 3;//=space?
321
+ var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
322
+ var S_ATTR_END = 5;//attr value end and no space(quot end)
323
+ var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
324
+ var S_TAG_CLOSE = 7;//closed el<el />
325
+
326
+ /**
327
+ * Creates an error that will not be caught by XMLReader aka the SAX parser.
328
+ *
329
+ * @param {string} message
330
+ * @param {any?} locator Optional, can provide details about the location in the source
331
+ * @constructor
332
+ */
333
+ function ParseError(message, locator) {
334
+ this.message = message;
335
+ this.locator = locator;
336
+ if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
337
+ }
338
+ ParseError.prototype = new Error();
339
+ ParseError.prototype.name = ParseError.name;
340
+
341
+ function XMLReader(){
342
+
343
+ }
344
+
345
+ XMLReader.prototype = {
346
+ parse:function(source,defaultNSMap,entityMap){
347
+ var domBuilder = this.domBuilder;
348
+ domBuilder.startDocument();
349
+ _copy(defaultNSMap ,defaultNSMap = {});
350
+ parse(source,defaultNSMap,entityMap,
351
+ domBuilder,this.errorHandler);
352
+ domBuilder.endDocument();
353
+ }
354
+ };
355
+ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
356
+ function fixedFromCharCode(code) {
357
+ // String.prototype.fromCharCode does not supports
358
+ // > 2 bytes unicode chars directly
359
+ if (code > 0xffff) {
360
+ code -= 0x10000;
361
+ var surrogate1 = 0xd800 + (code >> 10)
362
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
363
+
364
+ return String.fromCharCode(surrogate1, surrogate2);
365
+ } else {
366
+ return String.fromCharCode(code);
367
+ }
368
+ }
369
+ function entityReplacer(a){
370
+ var k = a.slice(1,-1);
371
+ if(k in entityMap){
372
+ return entityMap[k];
373
+ }else if(k.charAt(0) === '#'){
374
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
375
+ }else {
376
+ errorHandler.error('entity not found:'+a);
377
+ return a;
378
+ }
379
+ }
380
+ function appendText(end){//has some bugs
381
+ if(end>start){
382
+ var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
383
+ locator&&position(start);
384
+ domBuilder.characters(xt,0,end-start);
385
+ start = end;
386
+ }
387
+ }
388
+ function position(p,m){
389
+ while(p>=lineEnd && (m = linePattern.exec(source))){
390
+ lineStart = m.index;
391
+ lineEnd = lineStart + m[0].length;
392
+ locator.lineNumber++;
393
+ //console.log('line++:',locator,startPos,endPos)
394
+ }
395
+ locator.columnNumber = p-lineStart+1;
396
+ }
397
+ var lineStart = 0;
398
+ var lineEnd = 0;
399
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g;
400
+ var locator = domBuilder.locator;
401
+
402
+ var parseStack = [{currentNSMap:defaultNSMapCopy}];
403
+ var closeMap = {};
404
+ var start = 0;
405
+ while(true){
406
+ try{
407
+ var tagStart = source.indexOf('<',start);
408
+ if(tagStart<0){
409
+ if(!source.substr(start).match(/^\s*$/)){
410
+ var doc = domBuilder.doc;
411
+ var text = doc.createTextNode(source.substr(start));
412
+ doc.appendChild(text);
413
+ domBuilder.currentElement = text;
414
+ }
415
+ return;
416
+ }
417
+ if(tagStart>start){
418
+ appendText(tagStart);
419
+ }
420
+ switch(source.charAt(tagStart+1)){
421
+ case '/':
422
+ var end = source.indexOf('>',tagStart+3);
423
+ var tagName = source.substring(tagStart+2,end);
424
+ var config = parseStack.pop();
425
+ if(end<0){
426
+
427
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
428
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
429
+ end = tagStart+1+tagName.length;
430
+ }else if(tagName.match(/\s</)){
431
+ tagName = tagName.replace(/[\s<].*/,'');
432
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
433
+ end = tagStart+1+tagName.length;
434
+ }
435
+ var localNSMap = config.localNSMap;
436
+ var endMatch = config.tagName == tagName;
437
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase();
438
+ if(endIgnoreCaseMach){
439
+ domBuilder.endElement(config.uri,config.localName,tagName);
440
+ if(localNSMap){
441
+ for(var prefix in localNSMap){
442
+ domBuilder.endPrefixMapping(prefix) ;
443
+ }
444
+ }
445
+ if(!endMatch){
446
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
447
+ }
448
+ }else {
449
+ parseStack.push(config);
450
+ }
451
+
452
+ end++;
453
+ break;
454
+ // end elment
455
+ case '?':// <?...?>
456
+ locator&&position(tagStart);
457
+ end = parseInstruction(source,tagStart,domBuilder);
458
+ break;
459
+ case '!':// <!doctype,<![CDATA,<!--
460
+ locator&&position(tagStart);
461
+ end = parseDCC(source,tagStart,domBuilder,errorHandler);
462
+ break;
463
+ default:
464
+ locator&&position(tagStart);
465
+ var el = new ElementAttributes();
466
+ var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
467
+ //elStartEnd
468
+ var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
469
+ var len = el.length;
470
+
471
+
472
+ if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
473
+ el.closed = true;
474
+ if(!entityMap.nbsp){
475
+ errorHandler.warning('unclosed xml attribute');
476
+ }
477
+ }
478
+ if(locator && len){
479
+ var locator2 = copyLocator(locator,{});
480
+ //try{//attribute position fixed
481
+ for(var i = 0;i<len;i++){
482
+ var a = el[i];
483
+ position(a.offset);
484
+ a.locator = copyLocator(locator,{});
485
+ }
486
+ domBuilder.locator = locator2;
487
+ if(appendElement(el,domBuilder,currentNSMap)){
488
+ parseStack.push(el);
489
+ }
490
+ domBuilder.locator = locator;
491
+ }else {
492
+ if(appendElement(el,domBuilder,currentNSMap)){
493
+ parseStack.push(el);
494
+ }
495
+ }
496
+
497
+
498
+
499
+ if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
500
+ end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder);
501
+ }else {
502
+ end++;
503
+ }
504
+ }
505
+ }catch(e){
506
+ if (e instanceof ParseError) {
507
+ throw e;
508
+ }
509
+ errorHandler.error('element parse error: '+e);
510
+ end = -1;
511
+ }
512
+ if(end>start){
513
+ start = end;
514
+ }else {
515
+ //TODO: 这里有可能sax回退,有位置错误风险
516
+ appendText(Math.max(tagStart,start)+1);
517
+ }
518
+ }
519
+ }
520
+ function copyLocator(f,t){
521
+ t.lineNumber = f.lineNumber;
522
+ t.columnNumber = f.columnNumber;
523
+ return t;
524
+ }
525
+
526
+ /**
527
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
528
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
529
+ */
530
+ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
531
+
532
+ /**
533
+ * @param {string} qname
534
+ * @param {string} value
535
+ * @param {number} startIndex
536
+ */
537
+ function addAttribute(qname, value, startIndex) {
538
+ if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined');
539
+ el.addValue(qname, value, startIndex);
540
+ }
541
+ var attrName;
542
+ var value;
543
+ var p = ++start;
544
+ var s = S_TAG;//status
545
+ while(true){
546
+ var c = source.charAt(p);
547
+ switch(c){
548
+ case '=':
549
+ if(s === S_ATTR){//attrName
550
+ attrName = source.slice(start,p);
551
+ s = S_EQ;
552
+ }else if(s === S_ATTR_SPACE){
553
+ s = S_EQ;
554
+ }else {
555
+ //fatalError: equal must after attrName or space after attrName
556
+ throw new Error('attribute equal must after attrName'); // No known test case
557
+ }
558
+ break;
559
+ case '\'':
560
+ case '"':
561
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
562
+ ){//equal
563
+ if(s === S_ATTR){
564
+ errorHandler.warning('attribute value must after "="');
565
+ attrName = source.slice(start,p);
566
+ }
567
+ start = p+1;
568
+ p = source.indexOf(c,start);
569
+ if(p>0){
570
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
571
+ addAttribute(attrName, value, start-1);
572
+ s = S_ATTR_END;
573
+ }else {
574
+ //fatalError: no end quot match
575
+ throw new Error('attribute value no end \''+c+'\' match');
576
+ }
577
+ }else if(s == S_ATTR_NOQUOT_VALUE){
578
+ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
579
+ //console.log(attrName,value,start,p)
580
+ addAttribute(attrName, value, start);
581
+ //console.dir(el)
582
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
583
+ start = p+1;
584
+ s = S_ATTR_END;
585
+ }else {
586
+ //fatalError: no equal before
587
+ throw new Error('attribute value must after "="'); // No known test case
588
+ }
589
+ break;
590
+ case '/':
591
+ switch(s){
592
+ case S_TAG:
593
+ el.setTagName(source.slice(start,p));
594
+ case S_ATTR_END:
595
+ case S_TAG_SPACE:
596
+ case S_TAG_CLOSE:
597
+ s =S_TAG_CLOSE;
598
+ el.closed = true;
599
+ case S_ATTR_NOQUOT_VALUE:
600
+ case S_ATTR:
601
+ case S_ATTR_SPACE:
602
+ break;
603
+ //case S_EQ:
604
+ default:
605
+ throw new Error("attribute invalid close char('/')") // No known test case
606
+ }
607
+ break;
608
+ case ''://end document
609
+ errorHandler.error('unexpected end of input');
610
+ if(s == S_TAG){
611
+ el.setTagName(source.slice(start,p));
612
+ }
613
+ return p;
614
+ case '>':
615
+ switch(s){
616
+ case S_TAG:
617
+ el.setTagName(source.slice(start,p));
618
+ case S_ATTR_END:
619
+ case S_TAG_SPACE:
620
+ case S_TAG_CLOSE:
621
+ break;//normal
622
+ case S_ATTR_NOQUOT_VALUE://Compatible state
623
+ case S_ATTR:
624
+ value = source.slice(start,p);
625
+ if(value.slice(-1) === '/'){
626
+ el.closed = true;
627
+ value = value.slice(0,-1);
628
+ }
629
+ case S_ATTR_SPACE:
630
+ if(s === S_ATTR_SPACE){
631
+ value = attrName;
632
+ }
633
+ if(s == S_ATTR_NOQUOT_VALUE){
634
+ errorHandler.warning('attribute "'+value+'" missed quot(")!');
635
+ addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start);
636
+ }else {
637
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
638
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!');
639
+ }
640
+ addAttribute(value, value, start);
641
+ }
642
+ break;
643
+ case S_EQ:
644
+ throw new Error('attribute value missed!!');
645
+ }
646
+ // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
647
+ return p;
648
+ /*xml space '\x20' | #x9 | #xD | #xA; */
649
+ case '\u0080':
650
+ c = ' ';
651
+ default:
652
+ if(c<= ' '){//space
653
+ switch(s){
654
+ case S_TAG:
655
+ el.setTagName(source.slice(start,p));//tagName
656
+ s = S_TAG_SPACE;
657
+ break;
658
+ case S_ATTR:
659
+ attrName = source.slice(start,p);
660
+ s = S_ATTR_SPACE;
661
+ break;
662
+ case S_ATTR_NOQUOT_VALUE:
663
+ var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
664
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
665
+ addAttribute(attrName, value, start);
666
+ case S_ATTR_END:
667
+ s = S_TAG_SPACE;
668
+ break;
669
+ //case S_TAG_SPACE:
670
+ //case S_EQ:
671
+ //case S_ATTR_SPACE:
672
+ // void();break;
673
+ //case S_TAG_CLOSE:
674
+ //ignore warning
675
+ }
676
+ }else {//not space
677
+ //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
678
+ //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
679
+ switch(s){
680
+ //case S_TAG:void();break;
681
+ //case S_ATTR:void();break;
682
+ //case S_ATTR_NOQUOT_VALUE:void();break;
683
+ case S_ATTR_SPACE:
684
+ el.tagName;
685
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
686
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!');
687
+ }
688
+ addAttribute(attrName, attrName, start);
689
+ start = p;
690
+ s = S_ATTR;
691
+ break;
692
+ case S_ATTR_END:
693
+ errorHandler.warning('attribute space is required"'+attrName+'"!!');
694
+ case S_TAG_SPACE:
695
+ s = S_ATTR;
696
+ start = p;
697
+ break;
698
+ case S_EQ:
699
+ s = S_ATTR_NOQUOT_VALUE;
700
+ start = p;
701
+ break;
702
+ case S_TAG_CLOSE:
703
+ throw new Error("elements closed character '/' and '>' must be connected to");
704
+ }
705
+ }
706
+ }//end outer switch
707
+ //console.log('p++',p)
708
+ p++;
709
+ }
710
+ }
711
+ /**
712
+ * @return true if has new namespace define
713
+ */
714
+ function appendElement(el,domBuilder,currentNSMap){
715
+ var tagName = el.tagName;
716
+ var localNSMap = null;
717
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
718
+ var i = el.length;
719
+ while(i--){
720
+ var a = el[i];
721
+ var qName = a.qName;
722
+ var value = a.value;
723
+ var nsp = qName.indexOf(':');
724
+ if(nsp>0){
725
+ var prefix = a.prefix = qName.slice(0,nsp);
726
+ var localName = qName.slice(nsp+1);
727
+ var nsPrefix = prefix === 'xmlns' && localName;
728
+ }else {
729
+ localName = qName;
730
+ prefix = null;
731
+ nsPrefix = qName === 'xmlns' && '';
732
+ }
733
+ //can not set prefix,because prefix !== ''
734
+ a.localName = localName ;
735
+ //prefix == null for no ns prefix attribute
736
+ if(nsPrefix !== false){//hack!!
737
+ if(localNSMap == null){
738
+ localNSMap = {};
739
+ //console.log(currentNSMap,0)
740
+ _copy(currentNSMap,currentNSMap={});
741
+ //console.log(currentNSMap,1)
742
+ }
743
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
744
+ a.uri = 'http://www.w3.org/2000/xmlns/';
745
+ domBuilder.startPrefixMapping(nsPrefix, value);
746
+ }
747
+ }
748
+ var i = el.length;
749
+ while(i--){
750
+ a = el[i];
751
+ var prefix = a.prefix;
752
+ if(prefix){//no prefix attribute has no namespace
753
+ if(prefix === 'xml'){
754
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
755
+ }if(prefix !== 'xmlns'){
756
+ a.uri = currentNSMap[prefix || ''];
757
+
758
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
759
+ }
760
+ }
761
+ }
762
+ var nsp = tagName.indexOf(':');
763
+ if(nsp>0){
764
+ prefix = el.prefix = tagName.slice(0,nsp);
765
+ localName = el.localName = tagName.slice(nsp+1);
766
+ }else {
767
+ prefix = null;//important!!
768
+ localName = el.localName = tagName;
769
+ }
770
+ //no prefix element has default namespace
771
+ var ns = el.uri = currentNSMap[prefix || ''];
772
+ domBuilder.startElement(ns,localName,tagName,el);
773
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
774
+ //localNSMap = null
775
+ if(el.closed){
776
+ domBuilder.endElement(ns,localName,tagName);
777
+ if(localNSMap){
778
+ for(prefix in localNSMap){
779
+ domBuilder.endPrefixMapping(prefix);
780
+ }
781
+ }
782
+ }else {
783
+ el.currentNSMap = currentNSMap;
784
+ el.localNSMap = localNSMap;
785
+ //parseStack.push(el);
786
+ return true;
787
+ }
788
+ }
789
+ function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
790
+ if(/^(?:script|textarea)$/i.test(tagName)){
791
+ var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
792
+ var text = source.substring(elStartEnd+1,elEndStart);
793
+ if(/[&<]/.test(text)){
794
+ if(/^script$/i.test(tagName)){
795
+ //if(!/\]\]>/.test(text)){
796
+ //lexHandler.startCDATA();
797
+ domBuilder.characters(text,0,text.length);
798
+ //lexHandler.endCDATA();
799
+ return elEndStart;
800
+ //}
801
+ }//}else{//text area
802
+ text = text.replace(/&#?\w+;/g,entityReplacer);
803
+ domBuilder.characters(text,0,text.length);
804
+ return elEndStart;
805
+ //}
806
+
807
+ }
808
+ }
809
+ return elStartEnd+1;
810
+ }
811
+ function fixSelfClosed(source,elStartEnd,tagName,closeMap){
812
+ //if(tagName in closeMap){
813
+ var pos = closeMap[tagName];
814
+ if(pos == null){
815
+ //console.log(tagName)
816
+ pos = source.lastIndexOf('</'+tagName+'>');
817
+ if(pos<elStartEnd){//忘记闭合
818
+ pos = source.lastIndexOf('</'+tagName);
819
+ }
820
+ closeMap[tagName] =pos;
821
+ }
822
+ return pos<elStartEnd;
823
+ //}
824
+ }
825
+ function _copy(source,target){
826
+ for(var n in source){target[n] = source[n];}
827
+ }
828
+ function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
829
+ var next= source.charAt(start+2);
830
+ switch(next){
831
+ case '-':
832
+ if(source.charAt(start + 3) === '-'){
833
+ var end = source.indexOf('-->',start+4);
834
+ //append comment source.substring(4,end)//<!--
835
+ if(end>start){
836
+ domBuilder.comment(source,start+4,end-start-4);
837
+ return end+3;
838
+ }else {
839
+ errorHandler.error("Unclosed comment");
840
+ return -1;
841
+ }
842
+ }else {
843
+ //error
844
+ return -1;
845
+ }
846
+ default:
847
+ if(source.substr(start+3,6) == 'CDATA['){
848
+ var end = source.indexOf(']]>',start+9);
849
+ domBuilder.startCDATA();
850
+ domBuilder.characters(source,start+9,end-start-9);
851
+ domBuilder.endCDATA();
852
+ return end+3;
853
+ }
854
+ //<!DOCTYPE
855
+ //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
856
+ var matchs = split(source,start);
857
+ var len = matchs.length;
858
+ if(len>1 && /!doctype/i.test(matchs[0][0])){
859
+ var name = matchs[1][0];
860
+ var pubid = false;
861
+ var sysid = false;
862
+ if(len>3){
863
+ if(/^public$/i.test(matchs[2][0])){
864
+ pubid = matchs[3][0];
865
+ sysid = len>4 && matchs[4][0];
866
+ }else if(/^system$/i.test(matchs[2][0])){
867
+ sysid = matchs[3][0];
868
+ }
869
+ }
870
+ var lastMatch = matchs[len-1];
871
+ domBuilder.startDTD(name, pubid, sysid);
872
+ domBuilder.endDTD();
873
+
874
+ return lastMatch.index+lastMatch[0].length
875
+ }
876
+ }
877
+ return -1;
878
+ }
879
+
880
+
881
+
882
+ function parseInstruction(source,start,domBuilder){
883
+ var end = source.indexOf('?>',start);
884
+ if(end){
885
+ var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
886
+ if(match){
887
+ match[0].length;
888
+ domBuilder.processingInstruction(match[1], match[2]) ;
889
+ return end+2;
890
+ }else {//error
891
+ return -1;
892
+ }
893
+ }
894
+ return -1;
895
+ }
896
+
897
+ function ElementAttributes(){
898
+ this.attributeNames = {};
899
+ }
900
+ ElementAttributes.prototype = {
901
+ setTagName:function(tagName){
902
+ if(!tagNamePattern.test(tagName)){
903
+ throw new Error('invalid tagName:'+tagName)
904
+ }
905
+ this.tagName = tagName;
906
+ },
907
+ addValue:function(qName, value, offset) {
908
+ if(!tagNamePattern.test(qName)){
909
+ throw new Error('invalid attribute:'+qName)
910
+ }
911
+ this.attributeNames[qName] = this.length;
912
+ this[this.length++] = {qName:qName,value:value,offset:offset};
913
+ },
914
+ length:0,
915
+ getLocalName:function(i){return this[i].localName},
916
+ getLocator:function(i){return this[i].locator},
917
+ getQName:function(i){return this[i].qName},
918
+ getURI:function(i){return this[i].uri},
919
+ getValue:function(i){return this[i].value}
920
+ // ,getIndex:function(uri, localName)){
921
+ // if(localName){
922
+ //
923
+ // }else{
924
+ // var qName = uri
925
+ // }
926
+ // },
927
+ // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
928
+ // getType:function(uri,localName){}
929
+ // getType:function(i){},
930
+ };
931
+
932
+
933
+
934
+ function split(source,start){
935
+ var match;
936
+ var buf = [];
937
+ var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
938
+ reg.lastIndex = start;
939
+ reg.exec(source);//skip <
940
+ while(match = reg.exec(source)){
941
+ buf.push(match);
942
+ if(match[1])return buf;
943
+ }
944
+ }
945
+
946
+ sax.XMLReader = XMLReader;
947
+ sax.ParseError = ParseError;
948
+ return sax;
949
+ }
950
+
951
+ var dom = {};
952
+
953
+ var hasRequiredDom;
954
+
955
+ function requireDom () {
956
+ if (hasRequiredDom) return dom;
957
+ hasRequiredDom = 1;
958
+ function copy(src,dest){
959
+ for(var p in src){
960
+ dest[p] = src[p];
961
+ }
962
+ }
963
+ /**
964
+ ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
965
+ ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
966
+ */
967
+ function _extends(Class,Super){
968
+ var pt = Class.prototype;
969
+ if(!(pt instanceof Super)){
970
+ function t(){} t.prototype = Super.prototype;
971
+ t = new t();
972
+ copy(pt,t);
973
+ Class.prototype = pt = t;
974
+ }
975
+ if(pt.constructor != Class){
976
+ if(typeof Class != 'function'){
977
+ console.error("unknow Class:"+Class);
978
+ }
979
+ pt.constructor = Class;
980
+ }
981
+ }
982
+ var htmlns = 'http://www.w3.org/1999/xhtml' ;
983
+ // Node Types
984
+ var NodeType = {};
985
+ var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
986
+ var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
987
+ var TEXT_NODE = NodeType.TEXT_NODE = 3;
988
+ var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
989
+ var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
990
+ var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
991
+ var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
992
+ var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
993
+ var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
994
+ var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
995
+ var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
996
+ var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
997
+
998
+ // ExceptionCode
999
+ var ExceptionCode = {};
1000
+ var ExceptionMessage = {};
1001
+ ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
1002
+ ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
1003
+ var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
1004
+ ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
1005
+ ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
1006
+ ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
1007
+ ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
1008
+ var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
1009
+ ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
1010
+ var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
1011
+ //level2
1012
+ ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
1013
+ ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
1014
+ ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
1015
+ ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
1016
+ ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
1017
+
1018
+ /**
1019
+ * DOM Level 2
1020
+ * Object DOMException
1021
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
1022
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
1023
+ */
1024
+ function DOMException(code, message) {
1025
+ if(message instanceof Error){
1026
+ var error = message;
1027
+ }else {
1028
+ error = this;
1029
+ Error.call(this, ExceptionMessage[code]);
1030
+ this.message = ExceptionMessage[code];
1031
+ if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
1032
+ }
1033
+ error.code = code;
1034
+ if(message) this.message = this.message + ": " + message;
1035
+ return error;
1036
+ } DOMException.prototype = Error.prototype;
1037
+ copy(ExceptionCode,DOMException);
1038
+ /**
1039
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
1040
+ * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
1041
+ * The items in the NodeList are accessible via an integral index, starting from 0.
1042
+ */
1043
+ function NodeList() {
1044
+ } NodeList.prototype = {
1045
+ /**
1046
+ * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
1047
+ * @standard level1
1048
+ */
1049
+ length:0,
1050
+ /**
1051
+ * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
1052
+ * @standard level1
1053
+ * @param index unsigned long
1054
+ * Index into the collection.
1055
+ * @return Node
1056
+ * The node at the indexth position in the NodeList, or null if that is not a valid index.
1057
+ */
1058
+ item: function(index) {
1059
+ return this[index] || null;
1060
+ },
1061
+ toString:function(isHTML,nodeFilter){
1062
+ for(var buf = [], i = 0;i<this.length;i++){
1063
+ serializeToString(this[i],buf,isHTML,nodeFilter);
1064
+ }
1065
+ return buf.join('');
1066
+ }
1067
+ };
1068
+ function LiveNodeList(node,refresh){
1069
+ this._node = node;
1070
+ this._refresh = refresh;
1071
+ _updateLiveList(this);
1072
+ }
1073
+ function _updateLiveList(list){
1074
+ var inc = list._node._inc || list._node.ownerDocument._inc;
1075
+ if(list._inc != inc){
1076
+ var ls = list._refresh(list._node);
1077
+ //console.log(ls.length)
1078
+ __set__(list,'length',ls.length);
1079
+ copy(ls,list);
1080
+ list._inc = inc;
1081
+ }
1082
+ }
1083
+ LiveNodeList.prototype.item = function(i){
1084
+ _updateLiveList(this);
1085
+ return this[i];
1086
+ };
1087
+
1088
+ _extends(LiveNodeList,NodeList);
1089
+ /**
1090
+ *
1091
+ * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
1092
+ * NamedNodeMap objects in the DOM are live.
1093
+ * used for attributes or DocumentType entities
1094
+ */
1095
+ function NamedNodeMap() {
1096
+ }
1097
+ function _findNodeIndex(list,node){
1098
+ var i = list.length;
1099
+ while(i--){
1100
+ if(list[i] === node){return i}
1101
+ }
1102
+ }
1103
+
1104
+ function _addNamedNode(el,list,newAttr,oldAttr){
1105
+ if(oldAttr){
1106
+ list[_findNodeIndex(list,oldAttr)] = newAttr;
1107
+ }else {
1108
+ list[list.length++] = newAttr;
1109
+ }
1110
+ if(el){
1111
+ newAttr.ownerElement = el;
1112
+ var doc = el.ownerDocument;
1113
+ if(doc){
1114
+ oldAttr && _onRemoveAttribute(doc,el,oldAttr);
1115
+ _onAddAttribute(doc,el,newAttr);
1116
+ }
1117
+ }
1118
+ }
1119
+ function _removeNamedNode(el,list,attr){
1120
+ //console.log('remove attr:'+attr)
1121
+ var i = _findNodeIndex(list,attr);
1122
+ if(i>=0){
1123
+ var lastIndex = list.length-1;
1124
+ while(i<lastIndex){
1125
+ list[i] = list[++i];
1126
+ }
1127
+ list.length = lastIndex;
1128
+ if(el){
1129
+ var doc = el.ownerDocument;
1130
+ if(doc){
1131
+ _onRemoveAttribute(doc,el,attr);
1132
+ attr.ownerElement = null;
1133
+ }
1134
+ }
1135
+ }else {
1136
+ throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
1137
+ }
1138
+ }
1139
+ NamedNodeMap.prototype = {
1140
+ length:0,
1141
+ item:NodeList.prototype.item,
1142
+ getNamedItem: function(key) {
1143
+ // if(key.indexOf(':')>0 || key == 'xmlns'){
1144
+ // return null;
1145
+ // }
1146
+ //console.log()
1147
+ var i = this.length;
1148
+ while(i--){
1149
+ var attr = this[i];
1150
+ //console.log(attr.nodeName,key)
1151
+ if(attr.nodeName == key){
1152
+ return attr;
1153
+ }
1154
+ }
1155
+ },
1156
+ setNamedItem: function(attr) {
1157
+ var el = attr.ownerElement;
1158
+ if(el && el!=this._ownerElement){
1159
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
1160
+ }
1161
+ var oldAttr = this.getNamedItem(attr.nodeName);
1162
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
1163
+ return oldAttr;
1164
+ },
1165
+ /* returns Node */
1166
+ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
1167
+ var el = attr.ownerElement, oldAttr;
1168
+ if(el && el!=this._ownerElement){
1169
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
1170
+ }
1171
+ oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
1172
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
1173
+ return oldAttr;
1174
+ },
1175
+
1176
+ /* returns Node */
1177
+ removeNamedItem: function(key) {
1178
+ var attr = this.getNamedItem(key);
1179
+ _removeNamedNode(this._ownerElement,this,attr);
1180
+ return attr;
1181
+
1182
+
1183
+ },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
1184
+
1185
+ //for level2
1186
+ removeNamedItemNS:function(namespaceURI,localName){
1187
+ var attr = this.getNamedItemNS(namespaceURI,localName);
1188
+ _removeNamedNode(this._ownerElement,this,attr);
1189
+ return attr;
1190
+ },
1191
+ getNamedItemNS: function(namespaceURI, localName) {
1192
+ var i = this.length;
1193
+ while(i--){
1194
+ var node = this[i];
1195
+ if(node.localName == localName && node.namespaceURI == namespaceURI){
1196
+ return node;
1197
+ }
1198
+ }
1199
+ return null;
1200
+ }
1201
+ };
1202
+ /**
1203
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
1204
+ */
1205
+ function DOMImplementation(/* Object */ features) {
1206
+ this._features = {};
1207
+ if (features) {
1208
+ for (var feature in features) {
1209
+ this._features = features[feature];
1210
+ }
1211
+ }
1212
+ }
1213
+ DOMImplementation.prototype = {
1214
+ hasFeature: function(/* string */ feature, /* string */ version) {
1215
+ var versions = this._features[feature.toLowerCase()];
1216
+ if (versions && (!version || version in versions)) {
1217
+ return true;
1218
+ } else {
1219
+ return false;
1220
+ }
1221
+ },
1222
+ // Introduced in DOM Level 2:
1223
+ createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
1224
+ var doc = new Document();
1225
+ doc.implementation = this;
1226
+ doc.childNodes = new NodeList();
1227
+ doc.doctype = doctype;
1228
+ if(doctype){
1229
+ doc.appendChild(doctype);
1230
+ }
1231
+ if(qualifiedName){
1232
+ var root = doc.createElementNS(namespaceURI,qualifiedName);
1233
+ doc.appendChild(root);
1234
+ }
1235
+ return doc;
1236
+ },
1237
+ // Introduced in DOM Level 2:
1238
+ createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
1239
+ var node = new DocumentType();
1240
+ node.name = qualifiedName;
1241
+ node.nodeName = qualifiedName;
1242
+ node.publicId = publicId;
1243
+ node.systemId = systemId;
1244
+ // Introduced in DOM Level 2:
1245
+ //readonly attribute DOMString internalSubset;
1246
+
1247
+ //TODO:..
1248
+ // readonly attribute NamedNodeMap entities;
1249
+ // readonly attribute NamedNodeMap notations;
1250
+ return node;
1251
+ }
1252
+ };
1253
+
1254
+
1255
+ /**
1256
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
1257
+ */
1258
+
1259
+ function Node() {
1260
+ }
1261
+ Node.prototype = {
1262
+ firstChild : null,
1263
+ lastChild : null,
1264
+ previousSibling : null,
1265
+ nextSibling : null,
1266
+ attributes : null,
1267
+ parentNode : null,
1268
+ childNodes : null,
1269
+ ownerDocument : null,
1270
+ nodeValue : null,
1271
+ namespaceURI : null,
1272
+ prefix : null,
1273
+ localName : null,
1274
+ // Modified in DOM Level 2:
1275
+ insertBefore:function(newChild, refChild){//raises
1276
+ return _insertBefore(this,newChild,refChild);
1277
+ },
1278
+ replaceChild:function(newChild, oldChild){//raises
1279
+ this.insertBefore(newChild,oldChild);
1280
+ if(oldChild){
1281
+ this.removeChild(oldChild);
1282
+ }
1283
+ },
1284
+ removeChild:function(oldChild){
1285
+ return _removeChild(this,oldChild);
1286
+ },
1287
+ appendChild:function(newChild){
1288
+ return this.insertBefore(newChild,null);
1289
+ },
1290
+ hasChildNodes:function(){
1291
+ return this.firstChild != null;
1292
+ },
1293
+ cloneNode:function(deep){
1294
+ return cloneNode(this.ownerDocument||this,this,deep);
1295
+ },
1296
+ // Modified in DOM Level 2:
1297
+ normalize:function(){
1298
+ var child = this.firstChild;
1299
+ while(child){
1300
+ var next = child.nextSibling;
1301
+ if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
1302
+ this.removeChild(next);
1303
+ child.appendData(next.data);
1304
+ }else {
1305
+ child.normalize();
1306
+ child = next;
1307
+ }
1308
+ }
1309
+ },
1310
+ // Introduced in DOM Level 2:
1311
+ isSupported:function(feature, version){
1312
+ return this.ownerDocument.implementation.hasFeature(feature,version);
1313
+ },
1314
+ // Introduced in DOM Level 2:
1315
+ hasAttributes:function(){
1316
+ return this.attributes.length>0;
1317
+ },
1318
+ lookupPrefix:function(namespaceURI){
1319
+ var el = this;
1320
+ while(el){
1321
+ var map = el._nsMap;
1322
+ //console.dir(map)
1323
+ if(map){
1324
+ for(var n in map){
1325
+ if(map[n] == namespaceURI){
1326
+ return n;
1327
+ }
1328
+ }
1329
+ }
1330
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
1331
+ }
1332
+ return null;
1333
+ },
1334
+ // Introduced in DOM Level 3:
1335
+ lookupNamespaceURI:function(prefix){
1336
+ var el = this;
1337
+ while(el){
1338
+ var map = el._nsMap;
1339
+ //console.dir(map)
1340
+ if(map){
1341
+ if(prefix in map){
1342
+ return map[prefix] ;
1343
+ }
1344
+ }
1345
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
1346
+ }
1347
+ return null;
1348
+ },
1349
+ // Introduced in DOM Level 3:
1350
+ isDefaultNamespace:function(namespaceURI){
1351
+ var prefix = this.lookupPrefix(namespaceURI);
1352
+ return prefix == null;
1353
+ }
1354
+ };
1355
+
1356
+
1357
+ function _xmlEncoder(c){
1358
+ return c == '<' && '&lt;' ||
1359
+ c == '>' && '&gt;' ||
1360
+ c == '&' && '&amp;' ||
1361
+ c == '"' && '&quot;' ||
1362
+ '&#'+c.charCodeAt()+';'
1363
+ }
1364
+
1365
+
1366
+ copy(NodeType,Node);
1367
+ copy(NodeType,Node.prototype);
1368
+
1369
+ /**
1370
+ * @param callback return true for continue,false for break
1371
+ * @return boolean true: break visit;
1372
+ */
1373
+ function _visitNode(node,callback){
1374
+ if(callback(node)){
1375
+ return true;
1376
+ }
1377
+ if(node = node.firstChild){
1378
+ do{
1379
+ if(_visitNode(node,callback)){return true}
1380
+ }while(node=node.nextSibling)
1381
+ }
1382
+ }
1383
+
1384
+
1385
+
1386
+ function Document(){
1387
+ }
1388
+ function _onAddAttribute(doc,el,newAttr){
1389
+ doc && doc._inc++;
1390
+ var ns = newAttr.namespaceURI ;
1391
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
1392
+ //update namespace
1393
+ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value;
1394
+ }
1395
+ }
1396
+ function _onRemoveAttribute(doc,el,newAttr,remove){
1397
+ doc && doc._inc++;
1398
+ var ns = newAttr.namespaceURI ;
1399
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
1400
+ //update namespace
1401
+ delete el._nsMap[newAttr.prefix?newAttr.localName:''];
1402
+ }
1403
+ }
1404
+ function _onUpdateChild(doc,el,newChild){
1405
+ if(doc && doc._inc){
1406
+ doc._inc++;
1407
+ //update childNodes
1408
+ var cs = el.childNodes;
1409
+ if(newChild){
1410
+ cs[cs.length++] = newChild;
1411
+ }else {
1412
+ //console.log(1)
1413
+ var child = el.firstChild;
1414
+ var i = 0;
1415
+ while(child){
1416
+ cs[i++] = child;
1417
+ child =child.nextSibling;
1418
+ }
1419
+ cs.length = i;
1420
+ }
1421
+ }
1422
+ }
1423
+
1424
+ /**
1425
+ * attributes;
1426
+ * children;
1427
+ *
1428
+ * writeable properties:
1429
+ * nodeValue,Attr:value,CharacterData:data
1430
+ * prefix
1431
+ */
1432
+ function _removeChild(parentNode,child){
1433
+ var previous = child.previousSibling;
1434
+ var next = child.nextSibling;
1435
+ if(previous){
1436
+ previous.nextSibling = next;
1437
+ }else {
1438
+ parentNode.firstChild = next;
1439
+ }
1440
+ if(next){
1441
+ next.previousSibling = previous;
1442
+ }else {
1443
+ parentNode.lastChild = previous;
1444
+ }
1445
+ _onUpdateChild(parentNode.ownerDocument,parentNode);
1446
+ return child;
1447
+ }
1448
+ /**
1449
+ * preformance key(refChild == null)
1450
+ */
1451
+ function _insertBefore(parentNode,newChild,nextChild){
1452
+ var cp = newChild.parentNode;
1453
+ if(cp){
1454
+ cp.removeChild(newChild);//remove and update
1455
+ }
1456
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
1457
+ var newFirst = newChild.firstChild;
1458
+ if (newFirst == null) {
1459
+ return newChild;
1460
+ }
1461
+ var newLast = newChild.lastChild;
1462
+ }else {
1463
+ newFirst = newLast = newChild;
1464
+ }
1465
+ var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
1466
+
1467
+ newFirst.previousSibling = pre;
1468
+ newLast.nextSibling = nextChild;
1469
+
1470
+
1471
+ if(pre){
1472
+ pre.nextSibling = newFirst;
1473
+ }else {
1474
+ parentNode.firstChild = newFirst;
1475
+ }
1476
+ if(nextChild == null){
1477
+ parentNode.lastChild = newLast;
1478
+ }else {
1479
+ nextChild.previousSibling = newLast;
1480
+ }
1481
+ do{
1482
+ newFirst.parentNode = parentNode;
1483
+ }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
1484
+ _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
1485
+ //console.log(parentNode.lastChild.nextSibling == null)
1486
+ if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
1487
+ newChild.firstChild = newChild.lastChild = null;
1488
+ }
1489
+ return newChild;
1490
+ }
1491
+ function _appendSingleChild(parentNode,newChild){
1492
+ var cp = newChild.parentNode;
1493
+ if(cp){
1494
+ var pre = parentNode.lastChild;
1495
+ cp.removeChild(newChild);//remove and update
1496
+ var pre = parentNode.lastChild;
1497
+ }
1498
+ var pre = parentNode.lastChild;
1499
+ newChild.parentNode = parentNode;
1500
+ newChild.previousSibling = pre;
1501
+ newChild.nextSibling = null;
1502
+ if(pre){
1503
+ pre.nextSibling = newChild;
1504
+ }else {
1505
+ parentNode.firstChild = newChild;
1506
+ }
1507
+ parentNode.lastChild = newChild;
1508
+ _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
1509
+ return newChild;
1510
+ //console.log("__aa",parentNode.lastChild.nextSibling == null)
1511
+ }
1512
+ Document.prototype = {
1513
+ //implementation : null,
1514
+ nodeName : '#document',
1515
+ nodeType : DOCUMENT_NODE,
1516
+ doctype : null,
1517
+ documentElement : null,
1518
+ _inc : 1,
1519
+
1520
+ insertBefore : function(newChild, refChild){//raises
1521
+ if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
1522
+ var child = newChild.firstChild;
1523
+ while(child){
1524
+ var next = child.nextSibling;
1525
+ this.insertBefore(child,refChild);
1526
+ child = next;
1527
+ }
1528
+ return newChild;
1529
+ }
1530
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
1531
+ this.documentElement = newChild;
1532
+ }
1533
+
1534
+ return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
1535
+ },
1536
+ removeChild : function(oldChild){
1537
+ if(this.documentElement == oldChild){
1538
+ this.documentElement = null;
1539
+ }
1540
+ return _removeChild(this,oldChild);
1541
+ },
1542
+ // Introduced in DOM Level 2:
1543
+ importNode : function(importedNode,deep){
1544
+ return importNode(this,importedNode,deep);
1545
+ },
1546
+ // Introduced in DOM Level 2:
1547
+ getElementById : function(id){
1548
+ var rtv = null;
1549
+ _visitNode(this.documentElement,function(node){
1550
+ if(node.nodeType == ELEMENT_NODE){
1551
+ if(node.getAttribute('id') == id){
1552
+ rtv = node;
1553
+ return true;
1554
+ }
1555
+ }
1556
+ });
1557
+ return rtv;
1558
+ },
1559
+
1560
+ getElementsByClassName: function(className) {
1561
+ var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
1562
+ return new LiveNodeList(this, function(base) {
1563
+ var ls = [];
1564
+ _visitNode(base.documentElement, function(node) {
1565
+ if(node !== base && node.nodeType == ELEMENT_NODE) {
1566
+ if(pattern.test(node.getAttribute('class'))) {
1567
+ ls.push(node);
1568
+ }
1569
+ }
1570
+ });
1571
+ return ls;
1572
+ });
1573
+ },
1574
+
1575
+ //document factory method:
1576
+ createElement : function(tagName){
1577
+ var node = new Element();
1578
+ node.ownerDocument = this;
1579
+ node.nodeName = tagName;
1580
+ node.tagName = tagName;
1581
+ node.childNodes = new NodeList();
1582
+ var attrs = node.attributes = new NamedNodeMap();
1583
+ attrs._ownerElement = node;
1584
+ return node;
1585
+ },
1586
+ createDocumentFragment : function(){
1587
+ var node = new DocumentFragment();
1588
+ node.ownerDocument = this;
1589
+ node.childNodes = new NodeList();
1590
+ return node;
1591
+ },
1592
+ createTextNode : function(data){
1593
+ var node = new Text();
1594
+ node.ownerDocument = this;
1595
+ node.appendData(data);
1596
+ return node;
1597
+ },
1598
+ createComment : function(data){
1599
+ var node = new Comment();
1600
+ node.ownerDocument = this;
1601
+ node.appendData(data);
1602
+ return node;
1603
+ },
1604
+ createCDATASection : function(data){
1605
+ var node = new CDATASection();
1606
+ node.ownerDocument = this;
1607
+ node.appendData(data);
1608
+ return node;
1609
+ },
1610
+ createProcessingInstruction : function(target,data){
1611
+ var node = new ProcessingInstruction();
1612
+ node.ownerDocument = this;
1613
+ node.tagName = node.target = target;
1614
+ node.nodeValue= node.data = data;
1615
+ return node;
1616
+ },
1617
+ createAttribute : function(name){
1618
+ var node = new Attr();
1619
+ node.ownerDocument = this;
1620
+ node.name = name;
1621
+ node.nodeName = name;
1622
+ node.localName = name;
1623
+ node.specified = true;
1624
+ return node;
1625
+ },
1626
+ createEntityReference : function(name){
1627
+ var node = new EntityReference();
1628
+ node.ownerDocument = this;
1629
+ node.nodeName = name;
1630
+ return node;
1631
+ },
1632
+ // Introduced in DOM Level 2:
1633
+ createElementNS : function(namespaceURI,qualifiedName){
1634
+ var node = new Element();
1635
+ var pl = qualifiedName.split(':');
1636
+ var attrs = node.attributes = new NamedNodeMap();
1637
+ node.childNodes = new NodeList();
1638
+ node.ownerDocument = this;
1639
+ node.nodeName = qualifiedName;
1640
+ node.tagName = qualifiedName;
1641
+ node.namespaceURI = namespaceURI;
1642
+ if(pl.length == 2){
1643
+ node.prefix = pl[0];
1644
+ node.localName = pl[1];
1645
+ }else {
1646
+ //el.prefix = null;
1647
+ node.localName = qualifiedName;
1648
+ }
1649
+ attrs._ownerElement = node;
1650
+ return node;
1651
+ },
1652
+ // Introduced in DOM Level 2:
1653
+ createAttributeNS : function(namespaceURI,qualifiedName){
1654
+ var node = new Attr();
1655
+ var pl = qualifiedName.split(':');
1656
+ node.ownerDocument = this;
1657
+ node.nodeName = qualifiedName;
1658
+ node.name = qualifiedName;
1659
+ node.namespaceURI = namespaceURI;
1660
+ node.specified = true;
1661
+ if(pl.length == 2){
1662
+ node.prefix = pl[0];
1663
+ node.localName = pl[1];
1664
+ }else {
1665
+ //el.prefix = null;
1666
+ node.localName = qualifiedName;
1667
+ }
1668
+ return node;
1669
+ }
1670
+ };
1671
+ _extends(Document,Node);
1672
+
1673
+
1674
+ function Element() {
1675
+ this._nsMap = {};
1676
+ } Element.prototype = {
1677
+ nodeType : ELEMENT_NODE,
1678
+ hasAttribute : function(name){
1679
+ return this.getAttributeNode(name)!=null;
1680
+ },
1681
+ getAttribute : function(name){
1682
+ var attr = this.getAttributeNode(name);
1683
+ return attr && attr.value || '';
1684
+ },
1685
+ getAttributeNode : function(name){
1686
+ return this.attributes.getNamedItem(name);
1687
+ },
1688
+ setAttribute : function(name, value){
1689
+ var attr = this.ownerDocument.createAttribute(name);
1690
+ attr.value = attr.nodeValue = "" + value;
1691
+ this.setAttributeNode(attr);
1692
+ },
1693
+ removeAttribute : function(name){
1694
+ var attr = this.getAttributeNode(name);
1695
+ attr && this.removeAttributeNode(attr);
1696
+ },
1697
+
1698
+ //four real opeartion method
1699
+ appendChild:function(newChild){
1700
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
1701
+ return this.insertBefore(newChild,null);
1702
+ }else {
1703
+ return _appendSingleChild(this,newChild);
1704
+ }
1705
+ },
1706
+ setAttributeNode : function(newAttr){
1707
+ return this.attributes.setNamedItem(newAttr);
1708
+ },
1709
+ setAttributeNodeNS : function(newAttr){
1710
+ return this.attributes.setNamedItemNS(newAttr);
1711
+ },
1712
+ removeAttributeNode : function(oldAttr){
1713
+ //console.log(this == oldAttr.ownerElement)
1714
+ return this.attributes.removeNamedItem(oldAttr.nodeName);
1715
+ },
1716
+ //get real attribute name,and remove it by removeAttributeNode
1717
+ removeAttributeNS : function(namespaceURI, localName){
1718
+ var old = this.getAttributeNodeNS(namespaceURI, localName);
1719
+ old && this.removeAttributeNode(old);
1720
+ },
1721
+
1722
+ hasAttributeNS : function(namespaceURI, localName){
1723
+ return this.getAttributeNodeNS(namespaceURI, localName)!=null;
1724
+ },
1725
+ getAttributeNS : function(namespaceURI, localName){
1726
+ var attr = this.getAttributeNodeNS(namespaceURI, localName);
1727
+ return attr && attr.value || '';
1728
+ },
1729
+ setAttributeNS : function(namespaceURI, qualifiedName, value){
1730
+ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
1731
+ attr.value = attr.nodeValue = "" + value;
1732
+ this.setAttributeNode(attr);
1733
+ },
1734
+ getAttributeNodeNS : function(namespaceURI, localName){
1735
+ return this.attributes.getNamedItemNS(namespaceURI, localName);
1736
+ },
1737
+
1738
+ getElementsByTagName : function(tagName){
1739
+ return new LiveNodeList(this,function(base){
1740
+ var ls = [];
1741
+ _visitNode(base,function(node){
1742
+ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
1743
+ ls.push(node);
1744
+ }
1745
+ });
1746
+ return ls;
1747
+ });
1748
+ },
1749
+ getElementsByTagNameNS : function(namespaceURI, localName){
1750
+ return new LiveNodeList(this,function(base){
1751
+ var ls = [];
1752
+ _visitNode(base,function(node){
1753
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
1754
+ ls.push(node);
1755
+ }
1756
+ });
1757
+ return ls;
1758
+
1759
+ });
1760
+ }
1761
+ };
1762
+ Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
1763
+ Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
1764
+
1765
+
1766
+ _extends(Element,Node);
1767
+ function Attr() {
1768
+ } Attr.prototype.nodeType = ATTRIBUTE_NODE;
1769
+ _extends(Attr,Node);
1770
+
1771
+
1772
+ function CharacterData() {
1773
+ } CharacterData.prototype = {
1774
+ data : '',
1775
+ substringData : function(offset, count) {
1776
+ return this.data.substring(offset, offset+count);
1777
+ },
1778
+ appendData: function(text) {
1779
+ text = this.data+text;
1780
+ this.nodeValue = this.data = text;
1781
+ this.length = text.length;
1782
+ },
1783
+ insertData: function(offset,text) {
1784
+ this.replaceData(offset,0,text);
1785
+
1786
+ },
1787
+ appendChild:function(newChild){
1788
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
1789
+ },
1790
+ deleteData: function(offset, count) {
1791
+ this.replaceData(offset,count,"");
1792
+ },
1793
+ replaceData: function(offset, count, text) {
1794
+ var start = this.data.substring(0,offset);
1795
+ var end = this.data.substring(offset+count);
1796
+ text = start + text + end;
1797
+ this.nodeValue = this.data = text;
1798
+ this.length = text.length;
1799
+ }
1800
+ };
1801
+ _extends(CharacterData,Node);
1802
+ function Text() {
1803
+ } Text.prototype = {
1804
+ nodeName : "#text",
1805
+ nodeType : TEXT_NODE,
1806
+ splitText : function(offset) {
1807
+ var text = this.data;
1808
+ var newText = text.substring(offset);
1809
+ text = text.substring(0, offset);
1810
+ this.data = this.nodeValue = text;
1811
+ this.length = text.length;
1812
+ var newNode = this.ownerDocument.createTextNode(newText);
1813
+ if(this.parentNode){
1814
+ this.parentNode.insertBefore(newNode, this.nextSibling);
1815
+ }
1816
+ return newNode;
1817
+ }
1818
+ };
1819
+ _extends(Text,CharacterData);
1820
+ function Comment() {
1821
+ } Comment.prototype = {
1822
+ nodeName : "#comment",
1823
+ nodeType : COMMENT_NODE
1824
+ };
1825
+ _extends(Comment,CharacterData);
1826
+
1827
+ function CDATASection() {
1828
+ } CDATASection.prototype = {
1829
+ nodeName : "#cdata-section",
1830
+ nodeType : CDATA_SECTION_NODE
1831
+ };
1832
+ _extends(CDATASection,CharacterData);
1833
+
1834
+
1835
+ function DocumentType() {
1836
+ } DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
1837
+ _extends(DocumentType,Node);
1838
+
1839
+ function Notation() {
1840
+ } Notation.prototype.nodeType = NOTATION_NODE;
1841
+ _extends(Notation,Node);
1842
+
1843
+ function Entity() {
1844
+ } Entity.prototype.nodeType = ENTITY_NODE;
1845
+ _extends(Entity,Node);
1846
+
1847
+ function EntityReference() {
1848
+ } EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
1849
+ _extends(EntityReference,Node);
1850
+
1851
+ function DocumentFragment() {
1852
+ } DocumentFragment.prototype.nodeName = "#document-fragment";
1853
+ DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
1854
+ _extends(DocumentFragment,Node);
1855
+
1856
+
1857
+ function ProcessingInstruction() {
1858
+ }
1859
+ ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
1860
+ _extends(ProcessingInstruction,Node);
1861
+ function XMLSerializer(){}
1862
+ XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
1863
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
1864
+ };
1865
+ Node.prototype.toString = nodeSerializeToString;
1866
+ function nodeSerializeToString(isHtml,nodeFilter){
1867
+ var buf = [];
1868
+ var refNode = this.nodeType == 9 && this.documentElement || this;
1869
+ var prefix = refNode.prefix;
1870
+ var uri = refNode.namespaceURI;
1871
+
1872
+ if(uri && prefix == null){
1873
+ //console.log(prefix)
1874
+ var prefix = refNode.lookupPrefix(uri);
1875
+ if(prefix == null){
1876
+ //isHTML = true;
1877
+ var visibleNamespaces=[
1878
+ {namespace:uri,prefix:null}
1879
+ //{namespace:uri,prefix:''}
1880
+ ];
1881
+ }
1882
+ }
1883
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
1884
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
1885
+ return buf.join('');
1886
+ }
1887
+ function needNamespaceDefine(node,isHTML, visibleNamespaces) {
1888
+ var prefix = node.prefix||'';
1889
+ var uri = node.namespaceURI;
1890
+ if (!prefix && !uri){
1891
+ return false;
1892
+ }
1893
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
1894
+ || uri == 'http://www.w3.org/2000/xmlns/'){
1895
+ return false;
1896
+ }
1897
+
1898
+ var i = visibleNamespaces.length;
1899
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
1900
+ while (i--) {
1901
+ var ns = visibleNamespaces[i];
1902
+ // get namespace prefix
1903
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
1904
+ if (ns.prefix == prefix){
1905
+ return ns.namespace != uri;
1906
+ }
1907
+ }
1908
+ //console.log(isHTML,uri,prefix=='')
1909
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
1910
+ // return false;
1911
+ //}
1912
+ //node.flag = '11111'
1913
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
1914
+ return true;
1915
+ }
1916
+ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
1917
+ if(nodeFilter){
1918
+ node = nodeFilter(node);
1919
+ if(node){
1920
+ if(typeof node == 'string'){
1921
+ buf.push(node);
1922
+ return;
1923
+ }
1924
+ }else {
1925
+ return;
1926
+ }
1927
+ //buf.sort.apply(attrs, attributeSorter);
1928
+ }
1929
+ switch(node.nodeType){
1930
+ case ELEMENT_NODE:
1931
+ if (!visibleNamespaces) visibleNamespaces = [];
1932
+ visibleNamespaces.length;
1933
+ var attrs = node.attributes;
1934
+ var len = attrs.length;
1935
+ var child = node.firstChild;
1936
+ var nodeName = node.tagName;
1937
+
1938
+ isHTML = (htmlns === node.namespaceURI) ||isHTML;
1939
+ buf.push('<',nodeName);
1940
+
1941
+
1942
+
1943
+ for(var i=0;i<len;i++){
1944
+ // add namespaces for attributes
1945
+ var attr = attrs.item(i);
1946
+ if (attr.prefix == 'xmlns') {
1947
+ visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
1948
+ }else if(attr.nodeName == 'xmlns'){
1949
+ visibleNamespaces.push({ prefix: '', namespace: attr.value });
1950
+ }
1951
+ }
1952
+ for(var i=0;i<len;i++){
1953
+ var attr = attrs.item(i);
1954
+ if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
1955
+ var prefix = attr.prefix||'';
1956
+ var uri = attr.namespaceURI;
1957
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
1958
+ buf.push(ns, '="' , uri , '"');
1959
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
1960
+ }
1961
+ serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
1962
+ }
1963
+ // add namespace for current node
1964
+ if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
1965
+ var prefix = node.prefix||'';
1966
+ var uri = node.namespaceURI;
1967
+ if (uri) {
1968
+ // Avoid empty namespace value like xmlns:ds=""
1969
+ // Empty namespace URL will we produce an invalid XML document
1970
+ var ns = prefix ? ' xmlns:' + prefix : " xmlns";
1971
+ buf.push(ns, '="' , uri , '"');
1972
+ visibleNamespaces.push({ prefix: prefix, namespace:uri });
1973
+ }
1974
+ }
1975
+
1976
+ if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
1977
+ buf.push('>');
1978
+ //if is cdata child node
1979
+ if(isHTML && /^script$/i.test(nodeName)){
1980
+ while(child){
1981
+ if(child.data){
1982
+ buf.push(child.data);
1983
+ }else {
1984
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
1985
+ }
1986
+ child = child.nextSibling;
1987
+ }
1988
+ }else
1989
+ {
1990
+ while(child){
1991
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
1992
+ child = child.nextSibling;
1993
+ }
1994
+ }
1995
+ buf.push('</',nodeName,'>');
1996
+ }else {
1997
+ buf.push('/>');
1998
+ }
1999
+ // remove added visible namespaces
2000
+ //visibleNamespaces.length = startVisibleNamespaces;
2001
+ return;
2002
+ case DOCUMENT_NODE:
2003
+ case DOCUMENT_FRAGMENT_NODE:
2004
+ var child = node.firstChild;
2005
+ while(child){
2006
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
2007
+ child = child.nextSibling;
2008
+ }
2009
+ return;
2010
+ case ATTRIBUTE_NODE:
2011
+ /**
2012
+ * Well-formedness constraint: No < in Attribute Values
2013
+ * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
2014
+ * @see https://www.w3.org/TR/xml/#CleanAttrVals
2015
+ * @see https://www.w3.org/TR/xml/#NT-AttValue
2016
+ */
2017
+ return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
2018
+ case TEXT_NODE:
2019
+ /**
2020
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
2021
+ * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
2022
+ * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
2023
+ * `&amp;` and `&lt;` respectively.
2024
+ * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
2025
+ * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
2026
+ * when that string is not marking the end of a CDATA section.
2027
+ *
2028
+ * In the content of elements, character data is any string of characters
2029
+ * which does not contain the start-delimiter of any markup
2030
+ * and does not include the CDATA-section-close delimiter, `]]>`.
2031
+ *
2032
+ * @see https://www.w3.org/TR/xml/#NT-CharData
2033
+ */
2034
+ return buf.push(node.data
2035
+ .replace(/[<&]/g,_xmlEncoder)
2036
+ .replace(/]]>/g, ']]&gt;')
2037
+ );
2038
+ case CDATA_SECTION_NODE:
2039
+ return buf.push( '<![CDATA[',node.data,']]>');
2040
+ case COMMENT_NODE:
2041
+ return buf.push( "<!--",node.data,"-->");
2042
+ case DOCUMENT_TYPE_NODE:
2043
+ var pubid = node.publicId;
2044
+ var sysid = node.systemId;
2045
+ buf.push('<!DOCTYPE ',node.name);
2046
+ if(pubid){
2047
+ buf.push(' PUBLIC ', pubid);
2048
+ if (sysid && sysid!='.') {
2049
+ buf.push(' ', sysid);
2050
+ }
2051
+ buf.push('>');
2052
+ }else if(sysid && sysid!='.'){
2053
+ buf.push(' SYSTEM ', sysid, '>');
2054
+ }else {
2055
+ var sub = node.internalSubset;
2056
+ if(sub){
2057
+ buf.push(" [",sub,"]");
2058
+ }
2059
+ buf.push(">");
2060
+ }
2061
+ return;
2062
+ case PROCESSING_INSTRUCTION_NODE:
2063
+ return buf.push( "<?",node.target," ",node.data,"?>");
2064
+ case ENTITY_REFERENCE_NODE:
2065
+ return buf.push( '&',node.nodeName,';');
2066
+ //case ENTITY_NODE:
2067
+ //case NOTATION_NODE:
2068
+ default:
2069
+ buf.push('??',node.nodeName);
2070
+ }
2071
+ }
2072
+ function importNode(doc,node,deep){
2073
+ var node2;
2074
+ switch (node.nodeType) {
2075
+ case ELEMENT_NODE:
2076
+ node2 = node.cloneNode(false);
2077
+ node2.ownerDocument = doc;
2078
+ //var attrs = node2.attributes;
2079
+ //var len = attrs.length;
2080
+ //for(var i=0;i<len;i++){
2081
+ //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
2082
+ //}
2083
+ case DOCUMENT_FRAGMENT_NODE:
2084
+ break;
2085
+ case ATTRIBUTE_NODE:
2086
+ deep = true;
2087
+ break;
2088
+ //case ENTITY_REFERENCE_NODE:
2089
+ //case PROCESSING_INSTRUCTION_NODE:
2090
+ ////case TEXT_NODE:
2091
+ //case CDATA_SECTION_NODE:
2092
+ //case COMMENT_NODE:
2093
+ // deep = false;
2094
+ // break;
2095
+ //case DOCUMENT_NODE:
2096
+ //case DOCUMENT_TYPE_NODE:
2097
+ //cannot be imported.
2098
+ //case ENTITY_NODE:
2099
+ //case NOTATION_NODE:
2100
+ //can not hit in level3
2101
+ //default:throw e;
2102
+ }
2103
+ if(!node2){
2104
+ node2 = node.cloneNode(false);//false
2105
+ }
2106
+ node2.ownerDocument = doc;
2107
+ node2.parentNode = null;
2108
+ if(deep){
2109
+ var child = node.firstChild;
2110
+ while(child){
2111
+ node2.appendChild(importNode(doc,child,deep));
2112
+ child = child.nextSibling;
2113
+ }
2114
+ }
2115
+ return node2;
2116
+ }
2117
+ //
2118
+ //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
2119
+ // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
2120
+ function cloneNode(doc,node,deep){
2121
+ var node2 = new node.constructor();
2122
+ for(var n in node){
2123
+ var v = node[n];
2124
+ if(typeof v != 'object' ){
2125
+ if(v != node2[n]){
2126
+ node2[n] = v;
2127
+ }
2128
+ }
2129
+ }
2130
+ if(node.childNodes){
2131
+ node2.childNodes = new NodeList();
2132
+ }
2133
+ node2.ownerDocument = doc;
2134
+ switch (node2.nodeType) {
2135
+ case ELEMENT_NODE:
2136
+ var attrs = node.attributes;
2137
+ var attrs2 = node2.attributes = new NamedNodeMap();
2138
+ var len = attrs.length;
2139
+ attrs2._ownerElement = node2;
2140
+ for(var i=0;i<len;i++){
2141
+ node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
2142
+ }
2143
+ break; case ATTRIBUTE_NODE:
2144
+ deep = true;
2145
+ }
2146
+ if(deep){
2147
+ var child = node.firstChild;
2148
+ while(child){
2149
+ node2.appendChild(cloneNode(doc,child,deep));
2150
+ child = child.nextSibling;
2151
+ }
2152
+ }
2153
+ return node2;
2154
+ }
2155
+
2156
+ function __set__(object,key,value){
2157
+ object[key] = value;
2158
+ }
2159
+ //do dynamic
2160
+ try{
2161
+ if(Object.defineProperty){
2162
+ Object.defineProperty(LiveNodeList.prototype,'length',{
2163
+ get:function(){
2164
+ _updateLiveList(this);
2165
+ return this.$$length;
2166
+ }
2167
+ });
2168
+ Object.defineProperty(Node.prototype,'textContent',{
2169
+ get:function(){
2170
+ return getTextContent(this);
2171
+ },
2172
+ set:function(data){
2173
+ switch(this.nodeType){
2174
+ case ELEMENT_NODE:
2175
+ case DOCUMENT_FRAGMENT_NODE:
2176
+ while(this.firstChild){
2177
+ this.removeChild(this.firstChild);
2178
+ }
2179
+ if(data || String(data)){
2180
+ this.appendChild(this.ownerDocument.createTextNode(data));
2181
+ }
2182
+ break;
2183
+ default:
2184
+ //TODO:
2185
+ this.data = data;
2186
+ this.value = data;
2187
+ this.nodeValue = data;
2188
+ }
2189
+ }
2190
+ });
2191
+
2192
+ function getTextContent(node){
2193
+ switch(node.nodeType){
2194
+ case ELEMENT_NODE:
2195
+ case DOCUMENT_FRAGMENT_NODE:
2196
+ var buf = [];
2197
+ node = node.firstChild;
2198
+ while(node){
2199
+ if(node.nodeType!==7 && node.nodeType !==8){
2200
+ buf.push(getTextContent(node));
2201
+ }
2202
+ node = node.nextSibling;
2203
+ }
2204
+ return buf.join('');
2205
+ default:
2206
+ return node.nodeValue;
2207
+ }
2208
+ }
2209
+ __set__ = function(object,key,value){
2210
+ //console.log(value)
2211
+ object['$$'+key] = value;
2212
+ };
2213
+ }
2214
+ }catch(e){//ie8
2215
+ }
2216
+
2217
+ //if(typeof require == 'function'){
2218
+ dom.Node = Node;
2219
+ dom.DOMException = DOMException;
2220
+ dom.DOMImplementation = DOMImplementation;
2221
+ dom.XMLSerializer = XMLSerializer;
2222
+ //}
2223
+ return dom;
2224
+ }
2225
+
2226
+ var hasRequiredDomParser;
2227
+
2228
+ function requireDomParser () {
2229
+ if (hasRequiredDomParser) return domParser;
2230
+ hasRequiredDomParser = 1;
2231
+ function DOMParser(options){
2232
+ this.options = options ||{locator:{}};
2233
+ }
2234
+
2235
+ DOMParser.prototype.parseFromString = function(source,mimeType){
2236
+ var options = this.options;
2237
+ var sax = new XMLReader();
2238
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
2239
+ var errorHandler = options.errorHandler;
2240
+ var locator = options.locator;
2241
+ var defaultNSMap = options.xmlns||{};
2242
+ var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
2243
+ var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
2244
+ if(locator){
2245
+ domBuilder.setDocumentLocator(locator);
2246
+ }
2247
+
2248
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
2249
+ sax.domBuilder = options.domBuilder || domBuilder;
2250
+ if(isHTML){
2251
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
2252
+ }
2253
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
2254
+ if(source && typeof source === 'string'){
2255
+ sax.parse(source,defaultNSMap,entityMap);
2256
+ }else {
2257
+ sax.errorHandler.error("invalid doc source");
2258
+ }
2259
+ return domBuilder.doc;
2260
+ };
2261
+ function buildErrorHandler(errorImpl,domBuilder,locator){
2262
+ if(!errorImpl){
2263
+ if(domBuilder instanceof DOMHandler){
2264
+ return domBuilder;
2265
+ }
2266
+ errorImpl = domBuilder ;
2267
+ }
2268
+ var errorHandler = {};
2269
+ var isCallback = errorImpl instanceof Function;
2270
+ locator = locator||{};
2271
+ function build(key){
2272
+ var fn = errorImpl[key];
2273
+ if(!fn && isCallback){
2274
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg);}:errorImpl;
2275
+ }
2276
+ errorHandler[key] = fn && function(msg){
2277
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
2278
+ }||function(){};
2279
+ }
2280
+ build('warning');
2281
+ build('error');
2282
+ build('fatalError');
2283
+ return errorHandler;
2284
+ }
2285
+
2286
+ //console.log('#\n\n\n\n\n\n\n####')
2287
+ /**
2288
+ * +ContentHandler+ErrorHandler
2289
+ * +LexicalHandler+EntityResolver2
2290
+ * -DeclHandler-DTDHandler
2291
+ *
2292
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
2293
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
2294
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
2295
+ */
2296
+ function DOMHandler() {
2297
+ this.cdata = false;
2298
+ }
2299
+ function position(locator,node){
2300
+ node.lineNumber = locator.lineNumber;
2301
+ node.columnNumber = locator.columnNumber;
2302
+ }
2303
+ /**
2304
+ * @see org.xml.sax.ContentHandler#startDocument
2305
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
2306
+ */
2307
+ DOMHandler.prototype = {
2308
+ startDocument : function() {
2309
+ this.doc = new DOMImplementation().createDocument(null, null, null);
2310
+ if (this.locator) {
2311
+ this.doc.documentURI = this.locator.systemId;
2312
+ }
2313
+ },
2314
+ startElement:function(namespaceURI, localName, qName, attrs) {
2315
+ var doc = this.doc;
2316
+ var el = doc.createElementNS(namespaceURI, qName||localName);
2317
+ var len = attrs.length;
2318
+ appendElement(this, el);
2319
+ this.currentElement = el;
2320
+
2321
+ this.locator && position(this.locator,el);
2322
+ for (var i = 0 ; i < len; i++) {
2323
+ var namespaceURI = attrs.getURI(i);
2324
+ var value = attrs.getValue(i);
2325
+ var qName = attrs.getQName(i);
2326
+ var attr = doc.createAttributeNS(namespaceURI, qName);
2327
+ this.locator &&position(attrs.getLocator(i),attr);
2328
+ attr.value = attr.nodeValue = value;
2329
+ el.setAttributeNode(attr);
2330
+ }
2331
+ },
2332
+ endElement:function(namespaceURI, localName, qName) {
2333
+ var current = this.currentElement;
2334
+ current.tagName;
2335
+ this.currentElement = current.parentNode;
2336
+ },
2337
+ startPrefixMapping:function(prefix, uri) {
2338
+ },
2339
+ endPrefixMapping:function(prefix) {
2340
+ },
2341
+ processingInstruction:function(target, data) {
2342
+ var ins = this.doc.createProcessingInstruction(target, data);
2343
+ this.locator && position(this.locator,ins);
2344
+ appendElement(this, ins);
2345
+ },
2346
+ ignorableWhitespace:function(ch, start, length) {
2347
+ },
2348
+ characters:function(chars, start, length) {
2349
+ chars = _toString.apply(this,arguments);
2350
+ //console.log(chars)
2351
+ if(chars){
2352
+ if (this.cdata) {
2353
+ var charNode = this.doc.createCDATASection(chars);
2354
+ } else {
2355
+ var charNode = this.doc.createTextNode(chars);
2356
+ }
2357
+ if(this.currentElement){
2358
+ this.currentElement.appendChild(charNode);
2359
+ }else if(/^\s*$/.test(chars)){
2360
+ this.doc.appendChild(charNode);
2361
+ //process xml
2362
+ }
2363
+ this.locator && position(this.locator,charNode);
2364
+ }
2365
+ },
2366
+ skippedEntity:function(name) {
2367
+ },
2368
+ endDocument:function() {
2369
+ this.doc.normalize();
2370
+ },
2371
+ setDocumentLocator:function (locator) {
2372
+ if(this.locator = locator){// && !('lineNumber' in locator)){
2373
+ locator.lineNumber = 0;
2374
+ }
2375
+ },
2376
+ //LexicalHandler
2377
+ comment:function(chars, start, length) {
2378
+ chars = _toString.apply(this,arguments);
2379
+ var comm = this.doc.createComment(chars);
2380
+ this.locator && position(this.locator,comm);
2381
+ appendElement(this, comm);
2382
+ },
2383
+
2384
+ startCDATA:function() {
2385
+ //used in characters() methods
2386
+ this.cdata = true;
2387
+ },
2388
+ endCDATA:function() {
2389
+ this.cdata = false;
2390
+ },
2391
+
2392
+ startDTD:function(name, publicId, systemId) {
2393
+ var impl = this.doc.implementation;
2394
+ if (impl && impl.createDocumentType) {
2395
+ var dt = impl.createDocumentType(name, publicId, systemId);
2396
+ this.locator && position(this.locator,dt);
2397
+ appendElement(this, dt);
2398
+ }
2399
+ },
2400
+ /**
2401
+ * @see org.xml.sax.ErrorHandler
2402
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
2403
+ */
2404
+ warning:function(error) {
2405
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
2406
+ },
2407
+ error:function(error) {
2408
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
2409
+ },
2410
+ fatalError:function(error) {
2411
+ throw new ParseError(error, this.locator);
2412
+ }
2413
+ };
2414
+ function _locator(l){
2415
+ if(l){
2416
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
2417
+ }
2418
+ }
2419
+ function _toString(chars,start,length){
2420
+ if(typeof chars == 'string'){
2421
+ return chars.substr(start,length)
2422
+ }else {//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
2423
+ if(chars.length >= start+length || start){
2424
+ return new java.lang.String(chars,start,length)+'';
2425
+ }
2426
+ return chars;
2427
+ }
2428
+ }
2429
+
2430
+ /*
2431
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
2432
+ * used method of org.xml.sax.ext.LexicalHandler:
2433
+ * #comment(chars, start, length)
2434
+ * #startCDATA()
2435
+ * #endCDATA()
2436
+ * #startDTD(name, publicId, systemId)
2437
+ *
2438
+ *
2439
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
2440
+ * #endDTD()
2441
+ * #startEntity(name)
2442
+ * #endEntity(name)
2443
+ *
2444
+ *
2445
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
2446
+ * IGNORED method of org.xml.sax.ext.DeclHandler
2447
+ * #attributeDecl(eName, aName, type, mode, value)
2448
+ * #elementDecl(name, model)
2449
+ * #externalEntityDecl(name, publicId, systemId)
2450
+ * #internalEntityDecl(name, value)
2451
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
2452
+ * IGNORED method of org.xml.sax.EntityResolver2
2453
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
2454
+ * #resolveEntity(publicId, systemId)
2455
+ * #getExternalSubset(name, baseURI)
2456
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
2457
+ * IGNORED method of org.xml.sax.DTDHandler
2458
+ * #notationDecl(name, publicId, systemId) {};
2459
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
2460
+ */
2461
+ "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
2462
+ DOMHandler.prototype[key] = function(){return null};
2463
+ });
2464
+
2465
+ /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
2466
+ function appendElement (hander,node) {
2467
+ if (!hander.currentElement) {
2468
+ hander.doc.appendChild(node);
2469
+ } else {
2470
+ hander.currentElement.appendChild(node);
2471
+ }
2472
+ }//appendChild and setAttributeNS are preformance key
2473
+
2474
+ //if(typeof require == 'function'){
2475
+ var htmlEntity = requireEntities();
2476
+ var sax = requireSax();
2477
+ var XMLReader = sax.XMLReader;
2478
+ var ParseError = sax.ParseError;
2479
+ var DOMImplementation = domParser.DOMImplementation = requireDom().DOMImplementation;
2480
+ domParser.XMLSerializer = requireDom().XMLSerializer ;
2481
+ domParser.DOMParser = DOMParser;
2482
+ domParser.__DOMHandler = DOMHandler;
2483
+ //}
2484
+ return domParser;
2485
+ }
2486
+
2487
+ var domParserExports = requireDomParser();
2488
+
2489
+ /**
2490
+ * Fetches a URL with retry logic for expired tokens.
2491
+ *
2492
+ * @param {string} url - The URL to fetch.
2493
+ * @param {string} clientId - The OFSC client ID.
2494
+ * @param {string} clientSecret - The OFSC client secret.
2495
+ * @param {string} instanceUrl - The OFSC instance URL.
2496
+ * @param {string} token - The current OAuth token.
2497
+ *
2498
+ * @returns {Promise<{ data: any; token: string }>} A promise which resolves to an object containing the parsed JSON data and the latest OAuth token.
2499
+ */
2500
+ const fetchWithRetry = async (url, clientId, clientSecret, instanceUrl, token, retries = 5, baseDelay = 500) => {
2501
+ const doFetch = async (bearer) => {
2502
+ return fetch(url, {
2503
+ method: "GET",
2504
+ headers: {
2505
+ Authorization: `Bearer ${bearer}`,
2506
+ Accept: "application/json"
2507
+ }
2508
+ });
2509
+ };
2510
+ console.log(`➡️ Fetching ${url}`);
2511
+ // Try with the current token
2512
+ let res = await doFetch(token);
2513
+ /* ---------- 401: refresh token ONCE per call ---------- */
2514
+ if (res.status === 401) {
2515
+ console.warn("⚠️ Token expired — renewing token…");
2516
+ token = await getOAuthToken(clientId, clientSecret, instanceUrl);
2517
+ res = await doFetch(token);
2518
+ }
2519
+ /* ---------- 429: retry with backoff ---------- */
2520
+ if (res.status === 429 && retries > 0) {
2521
+ const retryAfter = res.headers.get("Retry-After");
2522
+ console.log("⚠️ 429 received. Retrying...", retryAfter);
2523
+ const delay = retryAfter ? Number(retryAfter) * 1000 : baseDelay;
2524
+ console.warn(`⚠️ 429 received. Retrying in ${delay}ms... (${retries} left)`);
2525
+ await new Promise(r => setTimeout(r, delay));
2526
+ return fetchWithRetry(url, clientId, clientSecret, instanceUrl, token, retries - 1, baseDelay * 2);
2527
+ }
2528
+ // If still not OK → fail
2529
+ if (!res.ok) {
2530
+ const body = await res.text();
2531
+ throw new Error(`❌ Request failed: ${res.status} ${res.statusText}\n${body}`);
2532
+ }
2533
+ // Return parsed JSON + latest token
2534
+ return {
2535
+ data: await res.json(),
2536
+ token
2537
+ };
2538
+ };
2539
+ function saveCsv(rows, filePath) {
2540
+ if (!rows || rows.length === 0) {
2541
+ throw new Error("CSV creation failed: no rows provided.");
2542
+ }
2543
+ // Extract headers from the first row
2544
+ const headers = Object.keys(rows[0]);
2545
+ // Build CSV content
2546
+ const csvLines = [
2547
+ headers.join(","), // header row
2548
+ ...rows.map(row => headers.map(h => escapeCsvValue(row[h])).join(","))
2549
+ ];
2550
+ const csvContent = csvLines.join("\n");
2551
+ // Ensure directory exists
2552
+ const dir = path.dirname(filePath);
2553
+ if (!fs__default.existsSync(dir)) {
2554
+ fs__default.mkdirSync(dir, { recursive: true });
2555
+ }
2556
+ // Write the file
2557
+ fs__default.writeFileSync(filePath, csvContent);
2558
+ console.log(`CSV saved: ${filePath}`);
2559
+ }
2560
+ // Escape CSV fields
2561
+ function escapeCsvValue(value) {
2562
+ if (value == null)
2563
+ return "";
2564
+ if (typeof value === "object") {
2565
+ value = JSON.stringify(value);
2566
+ }
2567
+ const str = String(value);
2568
+ // Wrap in quotes if needed
2569
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
2570
+ return `"${str.replace(/"/g, '""')}"`;
2571
+ }
2572
+ return str;
2573
+ }
2574
+ function xmlNodeToObjects(xmlString, parentNodeName) {
2575
+ const parser = new domParserExports.DOMParser();
2576
+ const xml = parser.parseFromString(xmlString, "application/xml");
2577
+ const nodes = Array.from(xml.getElementsByTagName(parentNodeName));
2578
+ if (nodes.length === 0) {
2579
+ throw new Error(`No <${parentNodeName}> nodes found`);
2580
+ }
2581
+ return nodes.map(node => {
2582
+ var _a, _b;
2583
+ const obj = {};
2584
+ const fields = Array.from(node.getElementsByTagName("Field"));
2585
+ for (const field of fields) {
2586
+ const key = field.getAttribute("name");
2587
+ if (!key)
2588
+ continue;
2589
+ obj[key] = (_b = (_a = field.textContent) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : "";
2590
+ }
2591
+ return obj;
2592
+ });
2593
+ }
2594
+
2595
+ var index$8 = /*#__PURE__*/Object.freeze({
2596
+ __proto__: null,
2597
+ fetchWithRetry: fetchWithRetry,
2598
+ saveCsv: saveCsv,
2599
+ xmlNodeToObjects: xmlNodeToObjects
2600
+ });
2601
+
2602
+ // Validate YYYY-MM-DD format
2603
+ const isValidDate = (date) => /^\d{4}-\d{2}-\d{2}$/.test(date);
2604
+ /**
2605
+ * Fetches all activities from the OFSC instance.
2606
+ *
2607
+ * @param {string} clientId - The OFSC client ID.
2608
+ * @param {string} clientSecret - The OFSC client secret.
2609
+ * @param {string} instanceUrl - The OFSC instance URL.
2610
+ * @param {string} [q] - The query string to filter activities.
2611
+ * @param {string} [resources] - The resources to filter activities by. Required.
2612
+ * @param {string} [fields] - The fields to include in the response.
2613
+ * @param {string} [dateFrom] - The date from which to filter activities.
2614
+ * @param {string} [dateTo] - The date to which to filter activities.
2615
+ * @returns {Promise<any[]>} A promise which resolves to an array of activity objects.
2616
+ * @throws {Error} If the date format is invalid or if the resources parameter is missing.
2617
+ */
2618
+ async function getAllActivities(clientId, clientSecret, instanceUrl, resources, dateFrom, dateTo, q, fields, includeNonScheduled = false) {
2619
+ // Validate date inputs
2620
+ if (!isValidDate(dateFrom) || !isValidDate(dateTo)) {
2621
+ throw new Error(`❌ Invalid date format. Expected YYYY-MM-DD.`);
2622
+ }
2623
+ let limit = 1000;
2624
+ let offset = 0;
2625
+ const allItems = [];
2626
+ // Prepare reusable token
2627
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
2628
+ while (true) {
2629
+ // Build URL cleanly
2630
+ const params = new URLSearchParams({
2631
+ offset: offset.toString(),
2632
+ limit: limit.toString()
2633
+ });
2634
+ if (q)
2635
+ params.append("q", q);
2636
+ if (resources)
2637
+ params.append("resources", resources);
2638
+ if (fields)
2639
+ params.append("fields", fields);
2640
+ if (dateFrom)
2641
+ params.append("dateFrom", dateFrom);
2642
+ if (dateTo)
2643
+ params.append("dateTo", dateTo);
2644
+ if (includeNonScheduled)
2645
+ params.append("includeNonScheduled", "true");
2646
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/?${params.toString()}`;
2647
+ console.error(url);
2648
+ console.log(`➡️ Fetching offset=${offset}, limit=${limit}`);
2649
+ const response = await fetchWithRetry(url, clientId, clientSecret, instanceUrl, token);
2650
+ const data = response.data;
2651
+ if (!data.items || data.items.length === 0) {
2652
+ console.log("✔ No more items found. Stopping pagination.");
2653
+ break;
2654
+ }
2655
+ allItems.push(...data.items);
2656
+ console.log(` ✔ Received ${data.items.length} items (Total: ${allItems.length})`);
2657
+ limit = data.limit;
2658
+ offset += limit;
2659
+ }
2660
+ return allItems;
2661
+ }
2662
+ async function getActivitybyId(clientId, clientSecret, instanceUrl, activityId, token = "") {
2663
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/${Number(activityId)}/`;
2664
+ console.log(`➡️ Fetching activity by ID: ${url}`);
2665
+ const response = await fetchWithRetry(url, clientId, clientSecret, instanceUrl, token);
2666
+ return response;
2667
+ }
2668
+
2669
+ var index$7 = /*#__PURE__*/Object.freeze({
2670
+ __proto__: null,
2671
+ getActivitybyId: getActivitybyId,
2672
+ getAllActivities: getAllActivities
2673
+ });
2674
+
2675
+ /**
2676
+ * Fetches all customer inventories related to the given activity.
2677
+ *
2678
+ * @param {string} clientId - The OFSC client ID.
2679
+ * @param {string} clientSecret - The OFSC client secret.
2680
+ * @param {string} instanceUrl - The OFSC instance URL.
2681
+ * @param {string} activityId - The ID of the activity to fetch customer inventories for.
2682
+ *
2683
+ * @returns {Promise<any[]>} A promise which resolves to an array of customer inventory objects.
2684
+ */
2685
+ async function getActivityCustomerInventories(clientId, clientSecret, instanceUrl, activityId, token = "") {
2686
+ const limit = 100;
2687
+ let offset = 0;
2688
+ // let token = await getOAuthToken(clientId, clientSecret, instanceUrl);
2689
+ const allItems = [];
2690
+ const fetchCustomerInventories = async (offset) => {
2691
+ const params = new URLSearchParams({
2692
+ offset: offset.toString(),
2693
+ limit: limit.toString()
2694
+ });
2695
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/${activityId}/customerInventories?${params}`;
2696
+ console.log(`➡️ Fetching offset=${offset}, limit=${limit}`);
2697
+ const response = await fetchWithRetry(url, clientId, clientSecret, instanceUrl, token);
2698
+ token = response.token;
2699
+ const data = response.data;
2700
+ if (!data.items || data.items.length === 0) {
2701
+ // console.log("✔ No more items found. Stopping pagination.");
2702
+ return;
2703
+ }
2704
+ allItems.push(...data.items);
2705
+ console.log(` ✔ Received ${data.items.length} items (Total: ${allItems.length}) for activity ${activityId}`);
2706
+ await fetchCustomerInventories(offset + limit);
2707
+ };
2708
+ await fetchCustomerInventories(offset);
2709
+ return allItems;
2710
+ }
2711
+ /**
2712
+ * Creates a new customer inventory related to the given activity.
2713
+ *
2714
+ * @param {string} clientId - The OFSC client ID.
2715
+ * @param {string} clientSecret - The OFSC client secret.
2716
+ * @param {string} instanceUrl - The OFSC instance URL.
2717
+ * @param {string} activityId - The ID of the activity to create a customer inventory for.
2718
+ * @param {object} payload - The customer inventory payload.
2719
+ *
2720
+ * @returns {Promise<object>} A promise which resolves to the created customer inventory object.
2721
+ */
2722
+ async function createActivityCustomerInventories(clientId, clientSecret, instanceUrl, activityId, payload) {
2723
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/activities/${activityId}/customerInventories`;
2724
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
2725
+ console.log(`➡️ creating ${url}`);
2726
+ const res = await fetch(url, {
2727
+ method: "POST",
2728
+ headers: {
2729
+ Authorization: `Bearer ${token}`,
2730
+ Accept: "application/json",
2731
+ "Content-Type": "application/json"
2732
+ },
2733
+ body: JSON.stringify(payload)
2734
+ });
2735
+ // if (!res.ok) {
2736
+ // return await res.json();
2737
+ // throw new Error(`❌ POST failed: ${res.status} ${res.statusText}`);
2738
+ // }
2739
+ return await res.json();
2740
+ }
2741
+
2742
+ var index$6 = /*#__PURE__*/Object.freeze({
2743
+ __proto__: null,
2744
+ createActivityCustomerInventories: createActivityCustomerInventories,
2745
+ getActivityCustomerInventories: getActivityCustomerInventories
2746
+ });
2747
+
2748
+ function flattenObject(obj, parentKey = "", result = {}) {
2749
+ for (const key in obj) {
2750
+ const newKey = parentKey ? `${parentKey}_${key}` : key;
2751
+ if (typeof obj[key] === "object" &&
2752
+ obj[key] !== null &&
2753
+ !Array.isArray(obj[key])) {
2754
+ flattenObject(obj[key], newKey, result);
2755
+ }
2756
+ else {
2757
+ result[newKey] = obj[key];
2758
+ }
2759
+ }
2760
+ return result;
2761
+ }
2762
+ async function fetchEventsPage(url, token, clientId, clientSecret, instanceUrl) {
2763
+ const res = await fetchWithRetry(url, clientId, clientSecret, instanceUrl, token);
2764
+ return {
2765
+ token: res.token,
2766
+ data: res.data
2767
+ };
2768
+ }
2769
+ function getNextDay(dateString) {
2770
+ // Parse manually to avoid timezone issues
2771
+ const [year, month, day] = dateString.split('-').map(Number);
2772
+ const date = new Date(year, month - 1, day);
2773
+ date.setDate(date.getDate() + 1);
2774
+ const pad = (n) => n.toString().padStart(2, '0');
2775
+ const y = date.getFullYear();
2776
+ const m = pad(date.getMonth() + 1);
2777
+ const d = pad(date.getDate());
2778
+ return `${y}-${m}-${d}`;
2779
+ }
2780
+ function processEventItems(items, sinceDate, output) {
2781
+ var _a, _b;
2782
+ for (const item of items) {
2783
+ const eventTime = item.time;
2784
+ // Stop if date changes
2785
+ if (eventTime.startsWith(getNextDay(sinceDate))) {
2786
+ console.log("Stopping at different event date:", eventTime);
2787
+ return false;
2788
+ }
2789
+ // Add activityId as first level field
2790
+ const activityId = (_b = (_a = item.activityDetails) === null || _a === void 0 ? void 0 : _a.activityId) !== null && _b !== void 0 ? _b : null;
2791
+ output.push({ activityId, ...item });
2792
+ }
2793
+ return true;
2794
+ }
2795
+ async function downloadAllEventsOfDay(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData) {
2796
+ console.log("Downloading events...OnlyData:", onlyData);
2797
+ let data = await downloadAllEventsOfDayCSV(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData);
2798
+ return data;
2799
+ }
2800
+ async function downloadAllEventsOfDayCSV(clientId, clientSecret, instanceUrl, subscriptionId, sinceDate, onlyData) {
2801
+ var _a, _b, _c;
2802
+ // All collected events
2803
+ const events = [];
2804
+ // Build initial request URL
2805
+ const baseUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/events`;
2806
+ const initialUrl = `${baseUrl}?subscriptionId=${encodeURIComponent(subscriptionId)}&since=${encodeURIComponent(sinceDate + " 00:00:00")}`;
2807
+ console.log("sinceDate", sinceDate);
2808
+ let token = await getOAuthToken(clientId, clientSecret, instanceUrl);
2809
+ // Get first page
2810
+ let firstPage = await fetchEventsPage(initialUrl, token, clientId, clientSecret, instanceUrl);
2811
+ token = firstPage.token;
2812
+ let nextPage = firstPage.data.nextPage;
2813
+ let found = firstPage.data.found;
2814
+ // Controls infinite loop
2815
+ let lastSeenPage = nextPage;
2816
+ let repeatedPageCount = 0;
2817
+ // Loop through pages
2818
+ while (found && nextPage) {
2819
+ const pageUrl = new URL(baseUrl);
2820
+ pageUrl.search = new URLSearchParams({
2821
+ subscriptionId,
2822
+ page: nextPage,
2823
+ limit: "1000",
2824
+ }).toString();
2825
+ const finalUrl = pageUrl.toString();
2826
+ const result = await fetchEventsPage(finalUrl, token, clientId, clientSecret, instanceUrl);
2827
+ token = result.token;
2828
+ const page = result.data;
2829
+ found = page.found;
2830
+ nextPage = page.nextPage;
2831
+ console.error("nextPage", nextPage, "Records:", (_a = page.items) === null || _a === void 0 ? void 0 : _a.length, "Time:", (_c = (_b = page.items) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.time);
2832
+ // Prevent infinite looping
2833
+ if (nextPage === lastSeenPage) {
2834
+ repeatedPageCount++;
2835
+ if (repeatedPageCount > 10) {
2836
+ console.warn("⚠️ Pagination repeating same page more than 10 times. Stopping.");
2837
+ break;
2838
+ }
2839
+ }
2840
+ else {
2841
+ lastSeenPage = nextPage;
2842
+ repeatedPageCount = 0;
2843
+ }
2844
+ // Add events
2845
+ if (page.items) {
2846
+ if (!processEventItems(page.items, sinceDate, events)) {
2847
+ break;
2848
+ }
2849
+ }
2850
+ else {
2851
+ console.warn("⚠️ No items found in page. Stopping.");
2852
+ break;
2853
+ }
2854
+ }
2855
+ // Save CSV
2856
+ const ts = Math.floor(Date.now() / 1000);
2857
+ const filename = `events-${sinceDate}_${ts}.csv`;
2858
+ const fullPath = path.resolve(filename);
2859
+ if (!onlyData) {
2860
+ saveCsv(events, fullPath);
2861
+ console.log(`✅ Saved ${events.length} events to: ${fullPath}`);
2862
+ }
2863
+ return events;
2864
+ }
2865
+
2866
+ var index$5 = /*#__PURE__*/Object.freeze({
2867
+ __proto__: null,
2868
+ downloadAllEventsOfDay: downloadAllEventsOfDay,
2869
+ downloadAllEventsOfDayCSV: downloadAllEventsOfDayCSV,
2870
+ flattenObject: flattenObject
2871
+ });
2872
+
2873
+ async function generateAllOnHandInventoryOfAllResourcesCSV(clientId, clientSecret, instanceUrl) {
2874
+ var _a, _b;
2875
+ let offset = 0;
2876
+ const limit = 100;
2877
+ const allUsers = [];
2878
+ let token = "";
2879
+ console.log("🚀 Starting all Resources Inventories export...");
2880
+ console.log("--------------------------------------------------");
2881
+ while (true) {
2882
+ const usersUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/resources/?offset=${offset}&limit=${limit}`;
2883
+ console.log(`➡️ Fetching users offset=${offset}`);
2884
+ const res = await fetchWithRetry(usersUrl, clientId, clientSecret, instanceUrl, token);
2885
+ token = res.token;
2886
+ const data = res.data;
2887
+ if (!((_a = data === null || data === void 0 ? void 0 : data.items) === null || _a === void 0 ? void 0 : _a.length)) {
2888
+ console.warn("⚠ No user items returned. Breaking.");
2889
+ break;
2890
+ }
2891
+ allUsers.push(...data.items);
2892
+ console.log(` ✔ Received ${data.items.length} resources (Total: ${allUsers.length})`);
2893
+ if (offset + limit >= data.totalResults)
2894
+ break;
2895
+ offset += limit;
2896
+ }
2897
+ console.log("--------------------------------------------------");
2898
+ console.log(`🧩 Total resources to process: ${allUsers.length}`);
2899
+ console.log("--------------------------------------------------");
2900
+ // 2. Fetch on hand inventories for each resource
2901
+ const rows = [];
2902
+ for (const [index, user] of allUsers.entries()) {
2903
+ console.log(`${index} 👤 Fetching Inventories for ${user.resourceId}`);
2904
+ if (user.status !== "active") {
2905
+ console.log(` ⚠ Skipping inactive resource ${user.resourceId}`);
2906
+ continue;
2907
+ }
2908
+ offset = 0;
2909
+ while (true) {
2910
+ const invUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/resources/${encodeURIComponent(user.resourceId)}/inventories/?offset=${offset}&limit=${limit}`;
2911
+ try {
2912
+ const res = await fetchWithRetry(invUrl, clientId, clientSecret, instanceUrl, token);
2913
+ token = res.token;
2914
+ const itemsData = res.data;
2915
+ const items = (_b = itemsData === null || itemsData === void 0 ? void 0 : itemsData.items) !== null && _b !== void 0 ? _b : [];
2916
+ if (!items || items.length === 0) {
2917
+ console.log(` ⚠ No Inventories found for ${user.resourceId}`);
2918
+ break;
2919
+ }
2920
+ for (const inv of items) {
2921
+ delete inv.links;
2922
+ delete inv.status;
2923
+ rows.push({ resourceName: user.name, resourceType: user.resourceType, resourceTimeZone: user.timeZoneIANA, ...inv, });
2924
+ }
2925
+ console.log(` ✔ Found ${items.length} Inventories`);
2926
+ if (offset + limit >= itemsData.totalResults)
2927
+ break;
2928
+ offset += limit;
2929
+ }
2930
+ catch (err) {
2931
+ console.error(`❌ Error fetching Inventories for ${user.resourceId}:`, err);
2932
+ console.log(` ⚠ Skipping invUrl ${invUrl}`);
2933
+ }
2934
+ }
2935
+ }
2936
+ console.log("--------------------------------------------------");
2937
+ console.log(`📦 Total rows: ${rows.length}`);
2938
+ console.log("--------------------------------------------------");
2939
+ const ts = Math.floor(Date.now() / 1000);
2940
+ const filename = `All_Resources_Inventories_${ts}.csv`;
2941
+ const fullPath = path.resolve(filename);
2942
+ saveCsv(rows, filename);
2943
+ console.log(`📁 CSV saved: ${fullPath}`);
2944
+ }
2945
+
2946
+ var index$4 = /*#__PURE__*/Object.freeze({
2947
+ __proto__: null,
2948
+ generateAllOnHandInventoryOfAllResourcesCSV: generateAllOnHandInventoryOfAllResourcesCSV
2949
+ });
2950
+
2951
+ var browser = {exports: {}};
2952
+
2953
+ var hasRequiredBrowser;
2954
+
2955
+ function requireBrowser () {
2956
+ if (hasRequiredBrowser) return browser.exports;
2957
+ hasRequiredBrowser = 1;
2958
+ (function (module, exports$1) {
2959
+
2960
+ // ref: https://github.com/tc39/proposal-global
2961
+ var getGlobal = function () {
2962
+ // the only reliable means to get the global object is
2963
+ // `Function('return this')()`
2964
+ // However, this causes CSP violations in Chrome apps.
2965
+ if (typeof self !== 'undefined') { return self; }
2966
+ if (typeof window !== 'undefined') { return window; }
2967
+ if (typeof commonjsGlobal !== 'undefined') { return commonjsGlobal; }
2968
+ throw new Error('unable to locate global object');
2969
+ };
2970
+
2971
+ var globalObject = getGlobal();
2972
+
2973
+ module.exports = exports$1 = globalObject.fetch;
2974
+
2975
+ // Needed for TypeScript and Webpack.
2976
+ if (globalObject.fetch) {
2977
+ exports$1.default = globalObject.fetch.bind(globalObject);
2978
+ }
2979
+
2980
+ exports$1.Headers = globalObject.Headers;
2981
+ exports$1.Request = globalObject.Request;
2982
+ exports$1.Response = globalObject.Response;
2983
+ } (browser, browser.exports));
2984
+ return browser.exports;
2985
+ }
2986
+
2987
+ var browserExports = requireBrowser();
2988
+ var fetch$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
2989
+
2990
+ async function downloadAllInventoryTypesCSV(clientId, clientSecret, instanceUrl) {
2991
+ let offset = 0;
2992
+ const limit = 100;
2993
+ let allItems = [];
2994
+ let totalFetched = 0;
2995
+ console.log("🚀 Starting all nventory type download...");
2996
+ console.log("-------------------------------------");
2997
+ while (true) {
2998
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/inventoryTypes/?offset=${offset}&limit=${limit}`;
2999
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3000
+ console.log(`➡️ Fetching offset=${offset} limit=${limit}`);
3001
+ const res = await fetch$1(url, {
3002
+ method: "GET",
3003
+ headers: {
3004
+ Authorization: `Bearer ${token}`,
3005
+ Accept: "application/json"
3006
+ }
3007
+ });
3008
+ if (!res.ok) {
3009
+ throw new Error(`❌ Fetch failed: ${res.status} ${res.statusText}`);
3010
+ }
3011
+ const data = (await res.json());
3012
+ allItems.push(...data.items);
3013
+ totalFetched += data.items.length;
3014
+ console.log(` ✔ Received ${data.items.length} items (Total: ${totalFetched})`);
3015
+ if (offset + limit >= data.totalResults)
3016
+ break;
3017
+ offset += limit;
3018
+ }
3019
+ console.log("-------------------------------------");
3020
+ console.log("🧩 Collecting all unique properties...");
3021
+ // Collect union of all properties
3022
+ const allProperties = new Set();
3023
+ for (const item of allItems) {
3024
+ for (const key of Object.keys(item)) {
3025
+ if (!["resources", "collaborationGroups", "resourceInternalIds", "links"].includes(key)) {
3026
+ allProperties.add(key);
3027
+ }
3028
+ }
3029
+ }
3030
+ const headers = Array.from(allProperties);
3031
+ console.log(`📝 Total unique fields: ${headers.length}`);
3032
+ // Build CSV rows
3033
+ const csvRows = [];
3034
+ csvRows.push(headers.join(","));
3035
+ for (const item of allItems) {
3036
+ const row = headers.map(field => {
3037
+ let value = item[field];
3038
+ if (field === "keys") {
3039
+ if (Array.isArray(value))
3040
+ return `"${value.join("|")}"`;
3041
+ if (value)
3042
+ return `"${String(value)}"`;
3043
+ return "";
3044
+ }
3045
+ // Objects → JSON-safe string
3046
+ if (typeof value === "object" && value !== null) {
3047
+ return `"${JSON.stringify(value).replace(/"/g, "'")}"`;
3048
+ }
3049
+ return value !== undefined ? `"${String(value).replace(/"/g, "'")}"` : "";
3050
+ });
3051
+ csvRows.push(row.join(","));
3052
+ }
3053
+ const filePath = "./all_inventories.csv";
3054
+ fs.writeFileSync(filePath, csvRows.join("\n"));
3055
+ console.log("-------------------------------------");
3056
+ console.log("✅ Inventories CSV Created Successfully!");
3057
+ console.log(`📁 File: ${filePath}`);
3058
+ console.log(`📦 Total Records: ${totalFetched}`);
3059
+ console.log(`🧩 Total Columns (Dynamic): ${headers.length}`);
3060
+ console.log(`🧩 Date Time: ${new Date()}`);
3061
+ console.log("-------------------------------------");
3062
+ }
3063
+ async function getInventoryTypesDetail(clientId, clientSecret, instanceUrl, label) {
3064
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/inventoryTypes/${label}`;
3065
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3066
+ const res = await fetch$1(url, {
3067
+ method: "GET",
3068
+ headers: {
3069
+ Authorization: `Bearer ${token}`,
3070
+ Accept: "application/json"
3071
+ }
3072
+ });
3073
+ if (!res.ok) {
3074
+ throw new Error(`❌ Fetch failed: ${res.status} ${res.statusText}`);
3075
+ }
3076
+ return await res.json();
3077
+ }
3078
+ async function updateCreateInventoryType(clientId, clientSecret, instanceUrl, label, payload) {
3079
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/inventoryTypes/${label}`;
3080
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3081
+ const res = await fetch$1(url, {
3082
+ method: "PUT",
3083
+ headers: {
3084
+ Authorization: `Bearer ${token}`,
3085
+ Accept: "application/json",
3086
+ "Content-Type": "application/json"
3087
+ },
3088
+ body: JSON.stringify(payload)
3089
+ });
3090
+ if (!res.ok) {
3091
+ throw new Error(`❌ PUT failed: ${res.status} ${res.statusText}`);
3092
+ }
3093
+ return await res.json();
3094
+ }
3095
+
3096
+ var index$3 = /*#__PURE__*/Object.freeze({
3097
+ __proto__: null,
3098
+ downloadAllInventoryTypesCSV: downloadAllInventoryTypesCSV,
3099
+ getInventoryTypesDetail: getInventoryTypesDetail,
3100
+ updateCreateInventoryType: updateCreateInventoryType
3101
+ });
3102
+
3103
+ async function downloadAllResourcesCSV(clientId, clientSecret, instanceUrl) {
3104
+ let offset = 0;
3105
+ const limit = 100;
3106
+ let allItems = [];
3107
+ let totalFetched = 0;
3108
+ console.log("🚀 Starting resource download...");
3109
+ console.log("-------------------------------------");
3110
+ while (true) {
3111
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/resources/?offset=${offset}&limit=${limit}`;
3112
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3113
+ console.log(`➡️ Fetching offset=${offset} limit=${limit}`);
3114
+ const res = await fetch$1(url, {
3115
+ method: "GET",
3116
+ headers: {
3117
+ Authorization: `Bearer ${token}`,
3118
+ Accept: "application/json"
3119
+ }
3120
+ });
3121
+ if (!res.ok) {
3122
+ throw new Error(`❌ Fetch failed: ${res.status} ${res.statusText}`);
3123
+ }
3124
+ const data = (await res.json());
3125
+ allItems.push(...data.items);
3126
+ totalFetched += data.items.length;
3127
+ console.log(` ✔ Received ${data.items.length} items (Total: ${totalFetched})`);
3128
+ if (offset + limit >= data.totalResults)
3129
+ break;
3130
+ offset += limit;
3131
+ }
3132
+ console.log("-------------------------------------");
3133
+ console.log("🧩 Collecting all unique properties...");
3134
+ // Collect union of all properties
3135
+ const allProperties = new Set();
3136
+ for (const item of allItems) {
3137
+ for (const key of Object.keys(item)) {
3138
+ if (!["links", "inventories", "users", "workZones", "workSkills", "workSchedules"].includes(key)) {
3139
+ allProperties.add(key);
3140
+ }
3141
+ }
3142
+ }
3143
+ const headers = Array.from(allProperties);
3144
+ console.log(`📝 Total unique fields: ${headers.length}`);
3145
+ // Build CSV rows
3146
+ const csvRows = [];
3147
+ csvRows.push(headers.join(","));
3148
+ for (const item of allItems) {
3149
+ const row = headers.map(field => {
3150
+ let value = item[field];
3151
+ if (field === "keys") {
3152
+ if (Array.isArray(value))
3153
+ return `"${value.join("|")}"`;
3154
+ if (value)
3155
+ return `"${String(value)}"`;
3156
+ return "";
3157
+ }
3158
+ // Objects → JSON-safe string
3159
+ if (typeof value === "object" && value !== null) {
3160
+ return `"${JSON.stringify(value).replace(/"/g, "'")}"`;
3161
+ }
3162
+ return value !== undefined ? `"${String(value).replace(/"/g, "'")}"` : "";
3163
+ });
3164
+ csvRows.push(row.join(","));
3165
+ }
3166
+ const filePath = "./resources.csv";
3167
+ fs.writeFileSync(filePath, csvRows.join("\n"));
3168
+ console.log("-------------------------------------");
3169
+ console.log("✅ Resource CSV Created Successfully!");
3170
+ console.log(`📁 File: ${filePath}`);
3171
+ console.log(`📦 Total Records: ${totalFetched}`);
3172
+ console.log(`🧩 Total Columns (Dynamic): ${headers.length}`);
3173
+ console.log(`🧩 Date Time: ${new Date()}`);
3174
+ console.log("-------------------------------------");
3175
+ }
3176
+
3177
+ var index$2 = /*#__PURE__*/Object.freeze({
3178
+ __proto__: null,
3179
+ downloadAllResourcesCSV: downloadAllResourcesCSV
3180
+ });
3181
+
3182
+ async function generateUsersCollaborationCSV(clientId, clientSecret, instanceUrl) {
3183
+ var _a, _b;
3184
+ let offset = 0;
3185
+ const limit = 100;
3186
+ const allUsers = [];
3187
+ let token = "";
3188
+ console.log("🚀 Starting Users Collaboration Groups export...");
3189
+ console.log("--------------------------------------------------");
3190
+ while (true) {
3191
+ const usersUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/users/?offset=${offset}&limit=${limit}`;
3192
+ console.log(`➡️ Fetching users offset=${offset}`);
3193
+ const res = await fetchWithRetry(usersUrl, clientId, clientSecret, instanceUrl, token);
3194
+ token = res.token;
3195
+ const data = res.data;
3196
+ if (!((_a = data === null || data === void 0 ? void 0 : data.items) === null || _a === void 0 ? void 0 : _a.length)) {
3197
+ console.warn("⚠ No user items returned. Breaking.");
3198
+ break;
3199
+ }
3200
+ allUsers.push(...data.items);
3201
+ console.log(` ✔ Received ${data.items.length} users (Total: ${allUsers.length})`);
3202
+ if (offset + limit >= data.totalResults)
3203
+ break;
3204
+ offset += limit;
3205
+ }
3206
+ console.log("--------------------------------------------------");
3207
+ console.log(`🧩 Total users to process: ${allUsers.length}`);
3208
+ console.log("--------------------------------------------------");
3209
+ // 2. Fetch collaboration groups for each user
3210
+ const rows = [];
3211
+ for (const user of allUsers) {
3212
+ console.log(`👤 Fetching groups for ${user.login}`);
3213
+ if (user.status !== "active") {
3214
+ console.log(` ⚠ Skipping inactive user ${user.login}`);
3215
+ continue;
3216
+ }
3217
+ try {
3218
+ const groupUrl = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/users/${user.login}/collaborationGroups`;
3219
+ const res = await fetchWithRetry(groupUrl, clientId, clientSecret, instanceUrl, token);
3220
+ token = res.token;
3221
+ const groupData = res.data;
3222
+ const groups = (_b = groupData === null || groupData === void 0 ? void 0 : groupData.items) !== null && _b !== void 0 ? _b : [];
3223
+ if (groups.length === 0) {
3224
+ console.log(` ⚠ No groups found for ${user.login}`);
3225
+ continue;
3226
+ }
3227
+ for (const group of groups) {
3228
+ rows.push({ ...group, login: user.login, userType: user.userType, timeZoneIANA: user.timeZoneIANA, userName: user.name });
3229
+ }
3230
+ console.log(` ✔ Found ${groups.length} groups`);
3231
+ }
3232
+ catch (err) {
3233
+ console.error(`❌ Error fetching groups for ${user.login}:`, err);
3234
+ }
3235
+ }
3236
+ console.log("--------------------------------------------------");
3237
+ console.log(`📦 Total rows: ${rows.length}`);
3238
+ console.log("--------------------------------------------------");
3239
+ const ts = Math.floor(Date.now() / 1000);
3240
+ const filename = `collaborationGroups_${ts}.csv`;
3241
+ const fullPath = path.resolve(filename);
3242
+ saveCsv(rows, filename);
3243
+ console.log(`📁 CSV saved: ${fullPath}`);
3244
+ }
3245
+
3246
+ async function downloadAllUsersCSV(clientId, clientSecret, instanceUrl) {
3247
+ let offset = 0;
3248
+ const limit = 100;
3249
+ let allItems = [];
3250
+ let totalFetched = 0;
3251
+ console.log("🚀 Starting users download...");
3252
+ console.log("-------------------------------------");
3253
+ while (true) {
3254
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscCore/v1/users/?offset=${offset}&limit=${limit}`;
3255
+ const token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3256
+ console.log(`➡️ Fetching offset=${offset} limit=${limit}`);
3257
+ const res = await fetch$1(url, {
3258
+ method: "GET",
3259
+ headers: {
3260
+ Authorization: `Bearer ${token}`,
3261
+ Accept: "application/json"
3262
+ }
3263
+ });
3264
+ if (!res.ok) {
3265
+ throw new Error(`❌ Fetch failed: ${res.status} ${res.statusText}`);
3266
+ }
3267
+ const data = (await res.json());
3268
+ allItems.push(...data.items);
3269
+ totalFetched += data.items.length;
3270
+ console.log(` ✔ Received ${data.items.length} items (Total: ${totalFetched})`);
3271
+ if (offset + limit >= data.totalResults)
3272
+ break;
3273
+ offset += limit;
3274
+ }
3275
+ console.log("-------------------------------------");
3276
+ console.log("🧩 Collecting all unique properties...");
3277
+ // Collect union of all properties
3278
+ const allProperties = new Set();
3279
+ for (const item of allItems) {
3280
+ for (const key of Object.keys(item)) {
3281
+ if (!["resources", "collaborationGroups", "resourceInternalIds", "links"].includes(key)) {
3282
+ allProperties.add(key);
3283
+ }
3284
+ }
3285
+ }
3286
+ const headers = Array.from(allProperties);
3287
+ console.log(`📝 Total unique fields: ${headers.length}`);
3288
+ // Build CSV rows
3289
+ const csvRows = [];
3290
+ csvRows.push(headers.join(","));
3291
+ for (const item of allItems) {
3292
+ const row = headers.map(field => {
3293
+ let value = item[field];
3294
+ if (field === "keys") {
3295
+ if (Array.isArray(value))
3296
+ return `"${value.join("|")}"`;
3297
+ if (value)
3298
+ return `"${String(value)}"`;
3299
+ return "";
3300
+ }
3301
+ // Objects → JSON-safe string
3302
+ if (typeof value === "object" && value !== null) {
3303
+ return `"${JSON.stringify(value).replace(/"/g, "'")}"`;
3304
+ }
3305
+ return value !== undefined ? `"${String(value).replace(/"/g, "'")}"` : "";
3306
+ });
3307
+ csvRows.push(row.join(","));
3308
+ }
3309
+ const filePath = "./users.csv";
3310
+ fs.writeFileSync(filePath, csvRows.join("\n"));
3311
+ console.log("-------------------------------------");
3312
+ console.log("✅ Users CSV Created Successfully!");
3313
+ console.log(`📁 File: ${filePath}`);
3314
+ console.log(`📦 Total Records: ${totalFetched}`);
3315
+ console.log(`🧩 Total Columns (Dynamic): ${headers.length}`);
3316
+ console.log(`🧩 Date Time: ${new Date()}`);
3317
+ console.log("-------------------------------------");
3318
+ }
3319
+ const OfscUserUtility = {
3320
+ generateUsersCollaborationCSV: require('./collaborationGroups').generateUsersCollaborationCSV,
3321
+ downloadAllUsersCSV
3322
+ };
3323
+
3324
+ var index$1 = /*#__PURE__*/Object.freeze({
3325
+ __proto__: null,
3326
+ default: OfscUserUtility,
3327
+ downloadAllUsersCSV: downloadAllUsersCSV,
3328
+ generateUsersCollaborationCSV: generateUsersCollaborationCSV
3329
+ });
3330
+
3331
+ async function downloadWorkZoneCSV(clientId, clientSecret, instanceUrl) {
3332
+ const startTime = Date.now();
3333
+ let offset = 0;
3334
+ const limit = 100;
3335
+ let totalWorkZones = 0;
3336
+ let totalKeys = 0;
3337
+ let csvRows = [
3338
+ "workZoneLabel,workZoneName,key,status,travelArea"
3339
+ ];
3340
+ while (true) {
3341
+ const url = `https://${instanceUrl}.fs.ocs.oraclecloud.com/rest/ofscMetadata/v1/workZones?offset=${offset}&limit=${limit}`;
3342
+ let token = await getOAuthToken(clientId, clientSecret, instanceUrl);
3343
+ const res = await fetch$1(url, {
3344
+ method: "GET",
3345
+ headers: {
3346
+ Authorization: `Bearer ${token}`,
3347
+ Accept: "application/json"
3348
+ }
3349
+ });
3350
+ if (!res.ok) {
3351
+ throw new Error(`Failed to fetch work zones: ${res.status} ${res.statusText}`);
3352
+ }
3353
+ const data = (await res.json());
3354
+ totalWorkZones += data.items.length;
3355
+ for (const item of data.items) {
3356
+ // Normalize keys (ensure it's always an array)
3357
+ const keys = Array.isArray(item.keys)
3358
+ ? item.keys
3359
+ : item.keys
3360
+ ? [item.keys]
3361
+ : [];
3362
+ totalKeys += keys.length;
3363
+ for (const key of keys) {
3364
+ csvRows.push(`${item.workZoneLabel},${item.workZoneName},${key},${item.status},${item.travelArea}`);
3365
+ }
3366
+ }
3367
+ if (!data.hasMore)
3368
+ break;
3369
+ offset = data.offset + limit;
3370
+ }
3371
+ const csv = csvRows.join("\n");
3372
+ const filePath = "./workzones.csv";
3373
+ fs.writeFileSync(filePath, csv);
3374
+ const endTime = Date.now();
3375
+ const durationSec = ((endTime - startTime) / 1000).toFixed(2);
3376
+ // --- Summary ---
3377
+ console.log("\n=== Work Zone Extraction Summary ===");
3378
+ console.log(`Total Work Zones Processed : ${totalWorkZones}`);
3379
+ console.log(`Total Keys Extracted : ${totalKeys}`);
3380
+ console.log(`CSV Saved To : ${filePath}`);
3381
+ console.log(`Time Taken : ${durationSec} sec`);
3382
+ console.log("====================================\n");
3383
+ console.log("✔ Work Zone CSV download completed.");
3384
+ }
3385
+
3386
+ var index = /*#__PURE__*/Object.freeze({
3387
+ __proto__: null,
3388
+ downloadWorkZoneCSV: downloadWorkZoneCSV
3389
+ });
3390
+
4
3391
  // Export all methods grouped by category
5
- exports.Activity = tslib_1.__importStar(require("./activities"));
6
- exports.ActivityInventories = tslib_1.__importStar(require("./activityInventories"));
7
- exports.Events = tslib_1.__importStar(require("./events"));
8
- exports.Inventory = tslib_1.__importStar(require("./inventory"));
9
- exports.InventoryType = tslib_1.__importStar(require("./inventoryTypes"));
10
- exports.OauthTokenService = tslib_1.__importStar(require("./oauthTokenService"));
11
- exports.Resource = tslib_1.__importStar(require("./resources"));
12
- exports.User = tslib_1.__importStar(require("./users"));
13
- exports.Utilities = tslib_1.__importStar(require("./utilities"));
14
- exports.WorkZone = tslib_1.__importStar(require("./workZones"));
15
- // Export types
16
- tslib_1.__exportStar(require("./types"), exports);
17
- var inventory_1 = require("./inventory");
18
- Object.defineProperty(exports, "generateAllOnHandInventoryOfAllResourcesCSV", { enumerable: true, get: function () { return inventory_1.generateAllOnHandInventoryOfAllResourcesCSV; } });
19
- var oauthTokenService_1 = require("./oauthTokenService");
20
- Object.defineProperty(exports, "getOAuthToken", { enumerable: true, get: function () { return oauthTokenService_1.getOAuthToken; } });
21
- var workZones_1 = require("./workZones");
22
- Object.defineProperty(exports, "downloadWorkZoneCSV", { enumerable: true, get: function () { return workZones_1.downloadWorkZoneCSV; } });
23
- var resources_1 = require("./resources");
24
- Object.defineProperty(exports, "downloadAllResourcesCSV", { enumerable: true, get: function () { return resources_1.downloadAllResourcesCSV; } });
25
- var users_1 = require("./users");
26
- Object.defineProperty(exports, "downloadAllUsersCSV", { enumerable: true, get: function () { return users_1.downloadAllUsersCSV; } });
27
- Object.defineProperty(exports, "generateUsersCollaborationCSV", { enumerable: true, get: function () { return users_1.generateUsersCollaborationCSV; } });
28
- var inventoryTypes_1 = require("./inventoryTypes");
29
- Object.defineProperty(exports, "downloadAllInventoryTypesCSV", { enumerable: true, get: function () { return inventoryTypes_1.downloadAllInventoryTypesCSV; } });
30
- Object.defineProperty(exports, "getInventoryTypesDetail", { enumerable: true, get: function () { return inventoryTypes_1.getInventoryTypesDetail; } });
31
- Object.defineProperty(exports, "updateCreateInventoryType", { enumerable: true, get: function () { return inventoryTypes_1.updateCreateInventoryType; } });
32
- var activities_1 = require("./activities");
33
- Object.defineProperty(exports, "getActivitybyId", { enumerable: true, get: function () { return activities_1.getActivitybyId; } });
34
- Object.defineProperty(exports, "getAllActivities", { enumerable: true, get: function () { return activities_1.getAllActivities; } });
35
- var activityInventories_1 = require("./activityInventories");
36
- Object.defineProperty(exports, "createActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.createActivityCustomerInventories; } });
37
- Object.defineProperty(exports, "getActivityCustomerInventories", { enumerable: true, get: function () { return activityInventories_1.getActivityCustomerInventories; } });
38
- var events_1 = require("./events");
39
- Object.defineProperty(exports, "downloadAllEventsOfDay", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDay; } });
40
- Object.defineProperty(exports, "downloadAllEventsOfDayCSV", { enumerable: true, get: function () { return events_1.downloadAllEventsOfDayCSV; } });
41
3392
  // Default export with all functionality
42
3393
  const OfscUtility = {
43
3394
  getOAuthToken: require('./oauthTokenService').getOAuthToken,
@@ -56,5 +3407,5 @@ const OfscUtility = {
56
3407
  generateAllOnHandInventoryOfAllResourcesCSV: require('./inventory').generateAllOnHandInventoryOfAllResourcesCSV,
57
3408
  getActivitybyId: require('./activities').getActivitybyId
58
3409
  };
59
- exports.default = OfscUtility;
60
- //# sourceMappingURL=ofsc-utility.esm.js.map
3410
+
3411
+ export { index$7 as Activity, index$6 as ActivityInventories, index$5 as Events, index$4 as Inventory, index$3 as InventoryType, index$9 as OauthTokenService, index$2 as Resource, index$1 as User, index$8 as Utilities, index as WorkZone, createActivityCustomerInventories, OfscUtility as default, downloadAllEventsOfDay, downloadAllEventsOfDayCSV, downloadAllInventoryTypesCSV, downloadAllResourcesCSV, downloadAllUsersCSV, downloadWorkZoneCSV, generateAllOnHandInventoryOfAllResourcesCSV, generateUsersCollaborationCSV, getActivityCustomerInventories, getActivitybyId, getAllActivities, getInventoryTypesDetail, getOAuthToken, updateCreateInventoryType };