text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { BlockBlobClient, BlobServiceClient } from "../src"; import { getBSU, recorderEnvSetup } from "./utils/index"; import { assert } from "chai"; import { appendToURLPath } from "../src/utils/utils.common"; import { record, Recorder } from "@azure-tools/test-recorder"; import * as dotenv from "dotenv"; import { ContainerClient } from "../src"; import { Context } from "mocha"; dotenv.config(); describe("Special Naming Tests", () => { let containerName: string; let containerClient: ContainerClient; let recorder: Recorder; let blobServiceClient: BlobServiceClient; beforeEach(async function(this: Context) { recorder = record(this, recorderEnvSetup); blobServiceClient = getBSU(); containerName = recorder.getUniqueName("1container-with-dash"); containerClient = blobServiceClient.getContainerClient(containerName); await containerClient.create(); }); afterEach(async function() { await containerClient.delete(); await recorder.stop(); }); it("Should work with special container and blob names with spaces", async () => { const blobName: string = recorder.getUniqueName("blob empty"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with spaces in URL string", async () => { const blobName: string = recorder.getUniqueName("blob empty"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with /", async () => { const blobName: string = recorder.getUniqueName("////blob/empty /another"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names with / in URL string", async () => { const blobName: string = recorder.getUniqueName("////blob/empty /another"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names uppercase", async () => { const blobName: string = recorder.getUniqueName("////Upper/blob/empty /another"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special container and blob names uppercase in URL string", async () => { const blobName: string = recorder.getUniqueName("////Upper/blob/empty /another"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters", async () => { const blobName: string = recorder.getUniqueName("////Upper/blob/empty /another 汉字"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob names Chinese characters in URL string", async () => { const blobName: string = recorder.getUniqueName("////Upper/blob/empty /another 汉字"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name characters", async () => { const blobName: string = recorder.getUniqueName( "汉字. special ~!@#$%^&*()_+`1234567890-={}|[]\\:\";'<>?,/'" ); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names prefix: blobName.replace(/\\/g, "/") }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name characters in URL string", async () => { const blobName: string = recorder.getUniqueName( "汉字. special ~!@#$%^&*()_+`1234567890-={}|[]\\:\";'<>?,/'" ); const blockBlobClient = new BlockBlobClient( // There are 2 special cases for a URL string: // Escape "%" when creating XxxClient object with URL strings // Escape "?" otherwise string after "?" will be treated as URL parameters appendToURLPath(containerClient.url, blobName.replace(/%/g, "%25").replace(/\?/g, "%3F")), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ // NOTICE: Azure Storage Server will replace "\" with "/" in the blob names prefix: blobName.replace(/\\/g, "/") }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian URI encoded", async () => { const blobName: string = recorder.getUniqueName("ру́сский язы́к"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian", async () => { const blobName: string = recorder.getUniqueName("ру́сский язы́к"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Russian in URL string", async () => { const blobName: string = recorder.getUniqueName("ру́сский язы́к"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic URI encoded", async () => { const blobName: string = recorder.getUniqueName("عربي/عربى"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic", async () => { const blobName: string = recorder.getUniqueName("عربي/عربى"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Arabic in URL string", async () => { const blobName: string = recorder.getUniqueName("عربي/عربى"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese URI encoded", async () => { const blobName: string = recorder.getUniqueName("にっぽんご/にほんご"); const blobNameEncoded: string = encodeURIComponent(blobName); const blockBlobClient = containerClient.getBlockBlobClient(blobNameEncoded); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobNameEncoded }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese", async () => { const blobName: string = recorder.getUniqueName("にっぽんご/にほんご"); const blockBlobClient = containerClient.getBlockBlobClient(blobName); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); it("Should work with special blob name Japanese in URL string", async () => { const blobName: string = recorder.getUniqueName("にっぽんご/にほんご"); const blockBlobClient = new BlockBlobClient( appendToURLPath(containerClient.url, blobName), (containerClient as any).pipeline ); await blockBlobClient.upload("A", 1); await blockBlobClient.getProperties(); const response = ( await containerClient .listBlobsFlat({ prefix: blobName }) .byPage() .next() ).value; assert.notDeepEqual(response.segment.blobItems.length, 0); }); });
the_stack
"use strict"; (function() { function log(code: string, message?: string, success?: boolean) { message = message || ''; if (document && document.body) { if (message) { message = $.views.converters.html(message); message = success === undefined ? "<br/>==== <b><em>" + message + "</em></b> ====<br/>" : message; } if (success === false) { message += ": <b>Failure</b>"; } if (code !== undefined) { code = $.views.converters.html(code); message = arguments.length>1 ? "<code>" + code + "...</code> " + message : "log: " + "<code>" + code + "</code> "; } $(document.body).append(message + "<br/>"); } else { if (success === undefined) { message = "==== " + message + " ===="; } else { if (code) { message = code + "... " + message; } if (!success) { message += ": Failure"; } } console.log(message); } } let assert = { equal: function(a: string, b: string, code: string, message?: string) { log(code, message || '', a === b); }, ok: function(a: boolean, code: string, message?: string) { log(code, message || '', a); }, testGroup: function(message: string) { log('', message); } }; /*<<<<<<<<<<<<<*/ assert.testGroup("$.templates, and basic render"); /*>>>>>>>>>>>>>*/ $(document.body).append('<script id="myTmpl" type="text/x-jsrender">{{:name}} </script>'); let tmpl = $.templates("#myTmpl"); assert.ok(tmpl.markup === "{{:name}} ", 'tmpl = $.templates("#myTmpl")'); assert.ok($.views.templates("#myTmpl").markup === "{{:name}} ", 'tmpl = $.views.templates("#myTmpl")'); assert.ok($.views.templates === $.templates, '$.views.templates === $.templates'); let data = { name: "Jo" }; let html = tmpl(data); assert.ok(html === "Jo ", 'tmpl(data)', 'Template as render function'); html = tmpl.render(data); assert.ok(html === "Jo ", 'tmpl.render(data)', 'Render function'); html = $("#myTmpl").render(data); assert.ok(html === "Jo ", '$("#myTmpl").render(data)', 'Render function on jQuery instance for script block'); $.templates("myTmpl", "#myTmpl"); html = $.render.myTmpl(data); assert.ok(html === "Jo ", '$.templates("myTmpl", "#myTmpl"); $.render.myTmpl(data)', 'Named template as expando on $.render'); html = $.templates.myTmpl(data); assert.ok(html === "Jo ", '$.templates("myTmpl", "#myTmpl"); $.templates.myTmpl(data)', 'Named template as expando on $.templates'); let array = [{ name: "Jo" }, { name: "Amy" }, { name: "Bob" }]; html = tmpl(array); assert.ok(html === "Jo Amy Bob ", 'tmpl(array)', 'Render array'); let helpers = { title: "Mr" }; tmpl = $.templates("tmplFromString", "{{:~title}} {{:name}}. "); assert.ok(tmpl.tmplName + tmpl.markup + tmpl.useViews === "tmplFromString{{:~title}} {{:name}}. true", 'tmpl.tmplName + tmpl.markup + tmpl.useViews', 'tmpl properties'); /*<<<<<<<<<<<<<*/ assert.testGroup("render() access helpers and set noIteration"); /*>>>>>>>>>>>>>*/ html = tmpl(array, helpers); assert.ok(html === "Mr Jo. Mr Amy. Mr Bob. ", 'tmpl(array, helpers)', 'Access helpers'); $(document.body).append('<script id="myTmpl2" type="text/x-jsrender">{{:length}}{{:~title}} {{:name}}. </script>'); html = $("#myTmpl2").render(array, helpers); assert.ok(html === "Mr Jo. Mr Amy. Mr Bob. ", '$("#myTmpl").render(array, helpers)', 'Access helpers'); tmpl = $.templates("{{:length}} {{for}}{{:~title}} {{:name}} {{/for}}"); html = tmpl(array, helpers, true); assert.ok(html === "3 Mr Jo Mr Amy Mr Bob ", 'tmpl(array, helpers, true)', 'Render array, no iteration'); html = tmpl.render(array, helpers, true); assert.ok(html === "3 Mr Jo Mr Amy Mr Bob ", 'tmpl.render(array, helpers, true)', 'Render array, no iteration'); $.views.helpers("title", "Sir"); html = tmpl(array, true); assert.ok(html === "3 Sir Jo Sir Amy Sir Bob ", 'tmpl(array, true)', 'Render array, no iteration'); html = tmpl.render(array, true); assert.ok(html === "3 Sir Jo Sir Amy Sir Bob ", 'tmpl.render(array, true)', 'Render array, no iteration'); html = $("#myTmpl2").render(array, helpers, true); assert.ok(html === "3Mr . ", '$("#myTmpl").render(array, helpers, true)', 'Render array, no iteration'); $.views.helpers("title", null); html = tmpl(array, true); assert.ok(html === "3 Jo Amy Bob ", '$.views.helpers("title", null); ...tmpl(array, true)', 'Unregister named helper, then render array, no iteration'); /*<<<<<<<<<<<<<*/ assert.testGroup("Compile template with private resources"); /*>>>>>>>>>>>>>*/ tmpl = $.templates({ markup: "{{:~title}}{{:~title2}}{{:~title3}} {{upper:name}} {{full/}} {{include tmpl='inner2'/}}{{include tmpl='inner'/}}", converters: { // private converter upper: function(val) { return val.toUpperCase(); } }, tags: { // private tag full: "{{upper:~title}} {{:name}}" }, helpers: { // private helper title: "Mr" }, templates: { // private template inner: "Inner: {{:~title}} {{:name}} {{full/}} {{short/}}" } }); $.views.converters({lower: function(val) {return val.toLowerCase();}}, tmpl); // Additional private converter $.templates("inner2", "Inner2", tmpl); // Additional private template $.views.helpers({title2: "Sir", title3: "Ms", myob: {amount: 33}, myfn: function(a: number) {return a + 10;} }, tmpl); // Additional private helpers $.views.tags("short", "{{lower:name}} ", tmpl); // Additional private tag html = tmpl(array); assert.ok(html === "MrSirMs JO MR Jo Inner2Inner: Mr Jo MR Jo jo MrSirMs AMY MR Amy Inner2Inner: Mr Amy MR Amy amy MrSirMs BOB MR Bob Inner2Inner: Mr Bob MR Bob bob ", 'tmpl = $.templates({markup: ..., converters: tags ... etc', 'Compile template with resources'); assert.equal( tmpl.converters.upper("jo") + tmpl.converters.lower("JO") + tmpl.tags.short.template.markup + tmpl.helpers.title + tmpl.helpers.title2 + tmpl.helpers.title3 + tmpl.helpers.myob.amount + tmpl.helpers.myfn(5) + tmpl.templates.inner.markup + tmpl.templates.inner2.markup, "JOjo{{lower:name}} MrSirMs3315Inner: {{:~title}} {{:name}} {{full/}} {{short/}}Inner2", 'tmpl.converters.upper("jo") ... +tmpl.templates.inner2.markup', "Accessing tmpl resources"); /*<<<<<<<<<<<<<*/ assert.testGroup("template.useViews"); /*>>>>>>>>>>>>>*/ assert.ok(!$.templates("{{for/}}").useViews, '$.templates("{{for/}}").useViews' , "useViews defaults to false"); assert.ok($.templates({ markup: "{{for/}}", useViews: true }).useViews, '$.templates({ ... useViews: true, ...})', "useViews forced to true"); assert.ok($.templates("{{for}}{{:#parent}}{{/for}}").useViews, '$.templates("{{for}}{{:#parent}}{{/for}}").useViews', "useViews defaults to true"); /*<<<<<<<<<<<<<*/ assert.testGroup("$.views.tags()"); /*>>>>>>>>>>>>>*/ let tag = $.views.tags("add", function(val1, val2) { return val1 + "|" + val2; }); let test = tag._is; tmpl = $.templates("{{add first last foo='FOO'/}} {{privateadd first last /}}"); tag = $.views.tags("privateadd", function(val1, val2) { return val1 + "!!" + val2; }, tmpl); test += tag._is; assert.equal(test + tmpl({first: "A", last: "B"}), "tagtagA|B A!!B", '$.views.tags("add", function() { ... })', "create tag from function, public or private"); $.views .tags({add: "{{: ~tagCtx.args[0] + '&' + ~tagCtx.args[1]}}"}) // Create public tag (replaces previous version) .tags({privateadd: "{{: ~tagCtx.args[0] + '$$' + ~tagCtx.args[1]}}"}, tmpl); // Create private tag (replaces previous version) assert.equal(tmpl({first: "A", last: "B"}), "A&B A$$B", '$.views.tags("add", "...")', "create tag from string, public or private"); $.views.tags("add", { mainElement:".a", // Set mainElem programmatically init: function(tagCtx, linkCtx, ctx) { this.baseApply(arguments); test = this.sortDataMap; this.foo = tagCtx.props.foo; test = this.render(); this.template = "some string"; this.template = {markup: "some content"}; }, render: function(val1, val2) { this.baseApply(arguments); test = this.sortDataMap; this.template = "some string"; this.template = {markup: "some content"}; return val1 + "==" + val2 + ":" + this.foo + "?" + this.ctx.x; }, template: {markup: "none"}, baseTag: "for", contentCtx: true, // function() { return "aaa"; }, convert: function(val) { return val.toLowerCase(); }, argDefault: true, bindTo: [0, "foo"], bindFrom: [0, "foo"], flow: false, ctx: { x: 'myctx' } }); $.views.tags({privateadd: { template: {markup: "none"}, }}, tmpl); assert.equal(tmpl({first: "A", last: "B"}), "a==B:FOO?myctx none", '$.views.tags("add", {...})', "create tag from tagOptions hash, public or private"); /*<<<<<<<<<<<<<*/ assert.testGroup("$.views.converters()"); /*>>>>>>>>>>>>>*/ let converter = $.views.converters("add", function(val1, val2) { return val1 + "|" + val2 + ", "; }); test = converter("a", "b"); tmpl = $.templates("{{add: first last}} {{privateadd: first last}}"); converter = $.views.converters({privateadd: function(val1, val2) { return val1 + "!!" + val2 + ", "; }}, tmpl) .converters.privateadd; // returns views, then access private converter resource 'privateadd' test += converter("c", "d"); assert.equal(test + "--" + tmpl({first: "A", last: "B"}), "a|b, c!!d, --A|B, A!!B, ", '$.views.converters("add", function() { ... })', "register converter, public or private"); converter = $.views.converters("add", null); assert.ok(converter === null && $.views.converters.add === undefined, '$.views.converters("...", null)', "unregister converter"); /*<<<<<<<<<<<<<*/ assert.testGroup("$.views.helpers()"); /*>>>>>>>>>>>>>*/ let helper = $.views.helpers("add", function(val1: string, val2: string) { return val1 + "|" + val2 + ", "; }); test = helper("a", "b"); tmpl = $.templates("{{:~add(first, last)}} {{:~privateadd(first, last)}}"); helper = $.views.helpers({privateadd: function(val1: string, val2: string) { return val1 + "!!" + val2 + ", "; }}, tmpl) .helpers.privateadd; // returns views, then access private helper resource 'privateadd' test += helper("c", "d"); assert.equal(test + "--" + tmpl({first: "A", last: "B"}), "a|b, c!!d, --A|B, A!!B, ", '$.views.helpers("add", function() { ... })', "register helper, public or private"); helper = $.views.helpers("add", null); assert.ok(helper === null && $.views.helpers.add === undefined, '$.views.helpers("...", null)', "unregister helper"); /*<<<<<<<<<<<<<*/ assert.testGroup("$.views.viewModels()"); /*>>>>>>>>>>>>>*/ let Book = $.views.viewModels({ getters: ["title", "price"], extend: {nameAndPrice: function(reverse?: boolean) { return reverse ? this._price + " for " + this._title : this._title + ": " + this._price; }} }); let book1 = Book("Hope", "$1.50"); assert.ok(book1.title() + ": " + book1.price() === "Hope: $1.50" && book1.nameAndPrice() === "Hope: $1.50" && book1.nameAndPrice(true) === "$1.50 for Hope", 'VM=$.views.viewModels(vmOptions)', "Create VM, instantiate and access members"); tmpl = $.templates("Title: {{:title()}}, Price: {{:price()}}, PriceName: {{:nameAndPrice(true)}}"); html = tmpl.render(book1); assert.ok(html === "Title: Hope, Price: $1.50, PriceName: $1.50 for Hope", 'tmpl.render(book1)', "Render vm instance with template"); book1.title(book1.title() + "+"); book1.price(book1.price() + "+"); html = tmpl.render(book1); assert.ok(html === "Title: Hope+, Price: $1.50+, PriceName: $1.50+ for Hope+", 'book1.title(newValue)', "Modify vm instance, with setters, then render template"); let MyVMs: JsViews.Hash<JsViews.ViewModel> = {}; Book = $.views.viewModels("Bk", { getters: ["title", "price"], extend: {nameAndPrice: function(reverse: boolean) { return reverse ? this._price + " for " + this._title : this._title + ":" + this._price; }} }); assert.ok(Book===$.views.viewModels.Bk, '$.views.viewModels("Bk", vmOptions)', "Register named VM"); Book = $.views.viewModels("Bk", { getters: ["title", "price"], extend: {nameAndPrice: function(reverse: boolean) { return reverse ? this._price + " for " + this._title : this._title + ":" + this._price; }} }, MyVMs); assert.ok(Book===MyVMs.Bk, '$.views.viewModels("Bk", vmOptions, MyVMs)', "Register named VM on local MyVMs collection"); $.views.viewModels({ Bk: { getters: ["title", "price"], extend: {nameAndPrice: function(reverse: boolean) { return reverse ? this._price + " for " + this._title : this._title + ":" + this._price; }} } }); $.views.viewModels({ Bk: { getters: ["title", "price"], extend: {nameAndPrice: function(reverse: boolean) { return reverse ? this._price + " for " + this._title : this._title + ":" + this._price; }} } }, MyVMs); test = $.views.viewModels.Bk("Hope", "$1.50").title(); assert.ok(test === "Hope", '$.views.viewModels({Bk: vmOptions})', "Register one or more named VMs"); test = MyVMs.Bk("Hope", "$1.50").title(); assert.ok(test === "Hope", '$.views.viewModels({Bk: vmOptions}, MyVMs)', "Register one or more named VMs on local myVms collection"); let bookData1 = {title: "Faith", price: "$10.50"}; // book (plain object) book1 = Book.map(bookData1); // book (instance of Book View Model) assert.ok(book1.title() === "Faith", 'Book.map(...)', "Instantiate vm instance from data, with map()"); book1.merge({ title: "Hope2", price: "$1.50" }); assert.ok(book1.title() === "Hope2", 'book.merge(...)', "Modify vm instance from data, with merge()"); test = book1.unmap(); assert.ok(test.title === "Hope2" && test.price === "$1.50", 'book.unmap()', "Round-trip data changes back to data, using unmap()"); let bookDataArray1 = [ // book array (plain objects) {title: "Hope", price: "$1.50"}, {title: "Courage", price: "$2.50"} ]; let booksArray1 = Book.map(bookDataArray1); // book array (instances of Book View Model) booksArray1.merge([ {title: "Hope2", price: "$1.50"}, {title: "Courage", price: "$222.50"} ]); test = booksArray1.unmap(); assert.ok(test[1].title === "Courage" && test[1].price === "$222.50", 'bookArray = Book.map(dataArray) bookArray.merge(...) bookArray.unmap()', "Round-trip data array to array of book vm instances"); tmpl = $.templates("Name: {{:name()}}, Street: {{:address().street()}}, Phones:" + "{{for phones()}} {{:number()}} ({{:person.name()}}) {{/for}}"); // The following code is from sample: https://www.jsviews.com/#viewmodelsapi@mergesampleadv plus use of parentRef let myVmCollection: JsViews.Hash<JsViews.ViewModel> = {}; interface Person { _name: string; _comment: string; _address: Address; phones: () => Phone[]; } interface Address { _street: string; } interface Phone { _number: string; id: string; } $.views.viewModels({ Person: { getters: [ {getter: "name", defaultVal: "No name"}, // Compiled name() get/set {getter: "address", type: "Address", defaultVal: defaultAddress}, {getter: "phones", type: "Phone", defaultVal: [], parentRef: "person"} ], extend: { name: myNameGetSet, // Override name() get/set addPhone: addPhone, comment: comment // Additional get/set property, not initialized by data) }, id: function(vm, plain) { // Callback function to determine 'identity' return vm.personId === plain.personId; } }, Address: { getters: ["street"] }, Phone: { getters: ["number"], id: "phoneId" // Treat phoneId as 'primary key', for identity } }, myVmCollection); // Store View Models (typed hierarchy) on myVmCollection // Override generated name() get/set function myNameGetSet(this: Person, val: string) { if (!arguments.length) { // This is standard compiled get/set code return this._name; // If there is no argument, use as a getter } this._name = val; // If there is an argument, use as a setter } // Method for Person class function addPhone(this: Person, phoneNo: string) { // Uses myVmCollection.Phone() to construct new instance this.phones().push(myVmCollection.Phone(phoneNo, "person", this)); } // get/set for comment (state on View Model instance, not initialized from data) function comment(this: Person, val: string) { if (!arguments.length) { return this._comment; // If there is no argument, use as a getter } this._comment = val; } function defaultAddress(this: {name: string}) { // Function providing default address if undefined in data return {street: 'No street for "' + this.name + '"'}; } // First version of data - array of objects (e.g. from JSON request): let peopleData = [ { personId: "1", address: { street: "2nd Ave" } }, { personId: "2", name: "Pete", phones: [ {number: "333 333 3333", phoneId: "2a"} ] } ]; // Second version of data - JSON string (e.g. new JSON request): let peopleData2 = '[{"personId":"2","name":"Peter","address":{"street":"11 1st Ave"},' + '"phones":[{"number":"111 111 9999","phoneId":"1a"},{"number":"333 333 9999","phoneId":"2a"}]}]'; // Instantiate View Model hierarchy using map() let people = myVmCollection.Person.map(peopleData); // Render template against people (array of Person instances) html = tmpl.render(people); assert.equal(html, 'Name: No name, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ', 'Person.map(peopleData)', "map data to full VM hierarchy"); people.merge(peopleData2); html = tmpl.render(people); assert.equal(html, 'Name: Peter, Street: 11 1st Ave, Phones: 111 111 9999 (Peter) 333 333 9999 (Peter) ', 'people.merge(peopleData2)', "Merge data on full hierarchy"); people.merge(peopleData); html = tmpl.render(people); assert.equal(html, 'Name: No name, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ', 'people.merge(peopleData)', "Merge back to previous data on full hierarchy"); people[0].name("newName"); html = tmpl.render(people); assert.equal(html, 'Name: newName, Street: 2nd Ave, Phones:Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ', 'people[0].name("newName")', "Change a property, deep in hierarchy"); people[0].addPhone("xxx xxx xxxx"); html = tmpl.render(people); assert.equal(html, 'Name: newName, Street: 2nd Ave, Phones: xxx xxx xxxx (newName) Name: Pete, Street: No street for "Pete", Phones: 333 333 3333 (Pete) ', 'people[0].addPhone("xxx xxx xxxx")', "Insert instance, deep in hierarchy"); let updatedPeopleData = people.unmap(); assert.ok(updatedPeopleData[0].name === "newName" && updatedPeopleData[0].phones[0].number === "xxx xxx xxxx", 'updatedPeopleData = people.unmap()', "Round-trip back to data"); /*<<<<<<<<<<<<<*/ assert.testGroup("view"); /*>>>>>>>>>>>>>*/ test = ''; $.views.helpers("hlp", 555); $.views.tags("mytag", { init: function(tagCtx, linkCtx, ctx) { let view = tagCtx.view; test += (view === this.tagCtx.view) + view.ctxPrm("foo") + "(" + view.getIndex() + view.get("array").get(true, "item").index + ")"; }, show: function(view) { test += (view.parent.views._1 === view && view.parent.parent === this.tagCtx.view) + view.parent.content.markup + view.type + view.parent.type + view.root.type + view.getRsc("helpers", "hlp"); } as (this: JsViews.Tag, view: JsViews.View) => void, template: "startTag {{include tmpl=#content /}} endTag" }); tmpl = $.templates("{{if true ~foo='FOO'}}{{for start=0 end=1}}{{mytag a 'b' 33}} in tag {{:~tag.show(#view)}} {{/mytag}}{{/for}}{{/if}}"); html = tmpl(); assert.equal(test, "trueFOO(00)true in tag {{:~tag.show(#view)}} includemytagdata555", 'view.get(), view.parent, view.data, view.root etc etc', "View APIs tested"); /*<<<<<<<<<<<<<*/ assert.testGroup("tagCtx"); /*>>>>>>>>>>>>>*/ $.views.tags("mytag", { init: function(tagCtx, linkCtx, ctx) { test = '' + linkCtx + tagCtx.ctxPrm("foo") + tagCtx.view.type + tagCtx.args[1] + tagCtx.props.bar + tagCtx.ctx.foo + (tagCtx.ctx === ctx) + tagCtx.bndArgs() + tagCtx.cvtArgs() + tagCtx.index + (this.tagCtxs[0] === tagCtx) + tagCtx.params.props.bar + (tagCtx.params.ctx && tagCtx.params.ctx.foo) + tagCtx.render(0, {foo: "FOO2"}) + (tagCtx.tag === this) + tagCtx.tag.tagName + (tagCtx.tmpl === null) + (tagCtx.tmpl && tagCtx.tmpl.markup) + (tagCtx.content && tagCtx.content.markup); } }); tmpl = $.templates("{{mytag a 'mode' bar=b ~foo='FOO'}}inner{{:~foo}}{{/mytag}}"); html = tmpl({a: "A", b: "B"}); assert.equal(test, "falseFOOdatamodeBFOOtrueA,modeA,mode0trueb'FOO'innerFOO2truemytagfalseinner{{:~foo}}inner{{:~foo}}", 'tagCtx.ctxPrm(), tagCtx.view, tagCtx.bndArgs(), tagCtx.params etc etc', "TagCtx APIs tested, {{myTag ...}}...{{/myTag}}"); tmpl = $.templates("{{mytag/}}"); html = tmpl({a: "A", b: "B"}); assert.equal(test, "falseundefineddataundefinedundefinedundefinedtrue0trueundefinedundefinedtruemytagfalsefalsefalse", 'tagCtx.ctxPrm(), tagCtx.view, tagCtx.bndArgs(), tagCtx.params etc etc', "TagCtx APIs tested, {{myTag/}}"); /*<<<<<<<<<<<<<*/ assert.testGroup("settings"); /*>>>>>>>>>>>>>*/ test = $.views.settings.delimiters(); $.views.settings.delimiters("<%", "%>", "&"); $.views.settings.allowCode(true); assert.equal("" + $.views.settings.delimiters() + $.views.settings.allowCode(), "<%,%>,&true", "settings.delimiters(), settings.allowCode()", "get/set settings"); $.views.settings.delimiters(test); $.views.settings.allowCode(false); })();
the_stack
* @module Frontstage */ import produce, { Draft } from "immer"; import { StagePanelLocation, StagePanelSection, UiEvent } from "@itwin/appui-abstract"; import { NineZoneState, PanelSide } from "@itwin/appui-layout-react"; import { FrontstageManager } from "../frontstage/FrontstageManager"; import { WidgetDef } from "../widgets/WidgetDef"; import { WidgetHost } from "../widgets/WidgetHost"; import { StagePanelMaxSizeSpec, StagePanelProps, StagePanelZoneProps, StagePanelZonesProps } from "./StagePanel"; import { getStableWidgetProps, ZoneLocation } from "../zones/Zone"; import { UiFramework } from "../UiFramework"; /** Enum for StagePanel state. * @public */ export enum StagePanelState { Off, Minimized, Open, Popup, } /** Panel State Changed Event Args interface. * @public */ export interface PanelStateChangedEventArgs { panelDef: StagePanelDef; panelState: StagePanelState; } /** Panel State Changed Event class. * @beta */ export class PanelStateChangedEvent extends UiEvent<PanelStateChangedEventArgs> { } /** @internal */ export interface PanelSizeChangedEventArgs { panelDef: StagePanelDef; size: number | undefined; } /** @internal */ export class PanelSizeChangedEvent extends UiEvent<PanelSizeChangedEventArgs> { } /** * A StagePanelDef represents each Stage Panel within a Frontstage. * @public */ export class StagePanelDef extends WidgetHost { private _panelState = StagePanelState.Open; private _defaultState = StagePanelState.Open; private _maxSizeSpec: StagePanelMaxSizeSpec | undefined; private _minSize: number | undefined; private _size: number | undefined; private _defaultSize: number | undefined; private _resizable = true; private _pinned = true; private _applicationData?: any; private _location: StagePanelLocation = StagePanelLocation.Left; private _panelZones = new StagePanelZonesDef(); /** Constructor for PanelDef. */ constructor() { super(); } /** @internal */ public get maxSizeSpec() { return this._maxSizeSpec; } /** @internal */ public get minSize() { return this._minSize; } /** Default size of the panel */ public get size() { // istanbul ignore next if ("1" === UiFramework.uiVersion) return this._size; // istanbul ignore else if (FrontstageManager.activeFrontstageDef) { const [_, size] = FrontstageManager.activeFrontstageDef.getPanelCurrentState(this); return size; } // istanbul ignore next return this._defaultSize; } public set size(size) { if (this._size === size) return; // istanbul ignore else if (UiFramework.uiVersion === "2") { const frontstageDef = FrontstageManager.activeFrontstageDef; // istanbul ignore else if (frontstageDef && frontstageDef.nineZoneState) { const side = toPanelSide(this.location); frontstageDef.nineZoneState = setPanelSize(frontstageDef.nineZoneState, side, size); const panel = frontstageDef.nineZoneState.panels[side]; if (panel.size === this._size) return; size = panel.size; } } this._size = size; FrontstageManager.onPanelSizeChangedEvent.emit({ panelDef: this, size, }); } /** Indicates whether the panel is resizable. */ // istanbul ignore next public get resizable(): boolean { return this._resizable; } /** Indicates whether the panel is pinned. */ public get pinned(): boolean { return this._pinned; } /** Any application data to attach to this Panel. */ public get applicationData(): any | undefined { return this._applicationData; } /** Location of panel. */ public get location(): StagePanelLocation { return this._location; } /** Panel state. Defaults to PanelState.Open. */ public get panelState() { if ("1" === UiFramework.uiVersion) return this._panelState; // istanbul ignore else if (FrontstageManager.activeFrontstageDef) { const [state] = FrontstageManager.activeFrontstageDef?.getPanelCurrentState(this); return state; } // istanbul ignore next return this.defaultState; } public set panelState(panelState: StagePanelState) { if (panelState === this._panelState) return; const frontstageDef = FrontstageManager.activeFrontstageDef; if (UiFramework.uiVersion === "2" && frontstageDef && frontstageDef.nineZoneState) { const side = toPanelSide(this.location); frontstageDef.nineZoneState = produce(frontstageDef.nineZoneState, (nineZone) => { const panel = nineZone.panels[side]; switch (panelState) { case StagePanelState.Minimized: { panel.collapsed = true; break; } case StagePanelState.Open: { panel.collapsed = false; break; } case StagePanelState.Off: { panel.collapsed = true; break; } } }); } this._panelState = panelState; FrontstageManager.onPanelStateChangedEvent.emit({ panelDef: this, panelState, }); } /** @internal */ public get defaultState() { return this._defaultState; } /** @internal */ public get defaultSize() { return this._defaultSize; } /** Panel zones. * @internal */ public get panelZones() { return this._panelZones; } /** @internal */ public initializeFromProps(props?: StagePanelProps, panelLocation?: StagePanelLocation): void { if (panelLocation !== undefined) this._location = panelLocation; if (!props) return; this._size = props.size; this._defaultSize = props.size; this._maxSizeSpec = props.maxSize; this._minSize = props.minSize; if (panelLocation !== undefined) this._location = panelLocation; if (props.defaultState !== undefined) { this._panelState = props.defaultState; this._defaultState = props.defaultState; } this._resizable = props.resizable; if (props.pinned !== undefined) this._pinned = props.pinned; if (props.applicationData !== undefined) this._applicationData = props.applicationData; if (props.panelZones) { this._panelZones.initializeFromProps(props.panelZones, this._location); } if (props.widgets) { props.widgets.forEach((widgetNode, index) => { const stableId = `uifw-sp-${StagePanelLocation[this._location]}-${index}`; const stableProps = getStableWidgetProps(widgetNode.props, stableId); const widgetDef = new WidgetDef(stableProps); this.addWidgetDef(widgetDef); }); } } /** Gets the list of Widgets. */ public override get widgetDefs(): ReadonlyArray<WidgetDef> { const widgetDefs = [...super.widgetDefs]; for (const [, panelZone] of this.panelZones) { widgetDefs.push(...panelZone.widgetDefs); } return widgetDefs; } /** Gets the list of Widgets (w/o StagePanelZone widgets). * @internal */ public get panelWidgetDefs() { return super.widgetDefs; } /** @internal */ public override updateDynamicWidgetDefs(stageId: string, stageUsage: string, location: ZoneLocation | StagePanelLocation, _section: StagePanelSection | undefined, allStageWidgetDefs: WidgetDef[], frontstageApplicationData?: any, ): void { this.panelZones.start.updateDynamicWidgetDefs(stageId, stageUsage, location, StagePanelSection.Start, allStageWidgetDefs, frontstageApplicationData); this.panelZones.end.updateDynamicWidgetDefs(stageId, stageUsage, location, StagePanelSection.Middle, allStageWidgetDefs, frontstageApplicationData); this.panelZones.end.updateDynamicWidgetDefs(stageId, stageUsage, location, StagePanelSection.End, allStageWidgetDefs, frontstageApplicationData); } } /** @internal */ export type StagePanelZoneDefKeys = keyof Pick<StagePanelZonesDef, "start" | "end">; const stagePanelZoneDefKeys: StagePanelZoneDefKeys[] = ["start", "end"]; /** @internal */ export class StagePanelZonesDef { private _start = new StagePanelZoneDef(); private _end = new StagePanelZoneDef(); public get start() { return this._start; } public get end() { return this._end; } /** @internal */ public initializeFromProps(props: StagePanelZonesProps, panelLocation: StagePanelLocation): void { if (props.start) { this.start.initializeFromProps(props.start, panelLocation, "start"); } if (props.middle) { this.end.initializeFromProps(props.middle, panelLocation, "end"); } if (props.end) { this.end.initializeFromProps(props.end, panelLocation, "end"); } } /** @internal */ public *[Symbol.iterator](): Iterator<[StagePanelZoneDefKeys, StagePanelZoneDef]> { for (const key of stagePanelZoneDefKeys) { const value = this[key]; yield [key, value]; } return undefined; } } /** @internal */ export class StagePanelZoneDef extends WidgetHost { /** @internal */ public initializeFromProps(props: StagePanelZoneProps, panelLocation: StagePanelLocation, panelZone: StagePanelZoneDefKeys): void { props.widgets.forEach((widgetNode, index) => { const stableId = `uifw-spz-${StagePanelLocation[panelLocation]}-${panelZone}-${index}`; const stableProps = getStableWidgetProps(widgetNode.props, stableId); const widgetDef = new WidgetDef(stableProps); this.addWidgetDef(widgetDef); }); } } /** @internal */ export function toPanelSide(location: StagePanelLocation): PanelSide { switch (location) { case StagePanelLocation.Bottom: case StagePanelLocation.BottomMost: return "bottom"; case StagePanelLocation.Left: return "left"; case StagePanelLocation.Right: return "right"; case StagePanelLocation.Top: case StagePanelLocation.TopMost: return "top"; } } /** @internal */ export const setPanelSize = produce(( nineZone: Draft<NineZoneState>, side: PanelSide, size: number | undefined, ) => { const panel = nineZone.panels[side]; panel.size = size === undefined ? size : Math.min(Math.max(size, panel.minSize), panel.maxSize); });
the_stack
import { APIFormField, FeatureBaseConfig, FormField, FormFieldBaseConfig, NormalisedBaseConfig, NormalisedFormField, ThemeBaseProps, } from "../../types"; import { RefObject } from "react"; import { GetRedirectionURLContext as AuthRecipeModuleGetRedirectionURLContext, OnHandleEventContext as AuthRecipeModuleOnHandleEventContext, PreAPIHookContext as AuthRecipeModulePreAPIHookContext, User, Config as AuthRecipeModuleConfig, NormalisedConfig as NormalisedAuthRecipeModuleConfig, UserInput as AuthRecipeModuleUserInput, UserInputOverride as AuthRecipeUserInputOverride, } from "../authRecipeModule/types"; import OverrideableBuilder from "supertokens-js-override"; import { ComponentOverride } from "../../components/componentOverride/componentOverride"; import { SignInHeader } from "./components/themes/signInAndUp/signInHeader"; import { SignIn } from "./components/themes/signInAndUp/signIn"; import { SignInFooter } from "./components/themes/signInAndUp/signInFooter"; import { SignInForm } from "./components/themes/signInAndUp/signInForm"; import { SignUp } from "./components/themes/signInAndUp/signUp"; import { SignUpFooter } from "./components/themes/signInAndUp/signUpFooter"; import { SignUpForm } from "./components/themes/signInAndUp/signUpForm"; import { SignUpHeader } from "./components/themes/signInAndUp/signUpHeader"; import { ResetPasswordEmail } from "./components/themes/resetPasswordUsingToken/resetPasswordEmail"; import { SubmitNewPassword } from "./components/themes/resetPasswordUsingToken/submitNewPassword"; export type ComponentOverrideMap = { EmailPasswordSignIn?: ComponentOverride<typeof SignIn>; EmailPasswordSignInFooter?: ComponentOverride<typeof SignInFooter>; EmailPasswordSignInForm?: ComponentOverride<typeof SignInForm>; EmailPasswordSignInHeader?: ComponentOverride<typeof SignInHeader>; EmailPasswordSignUp?: ComponentOverride<typeof SignUp>; EmailPasswordSignUpFooter?: ComponentOverride<typeof SignUpFooter>; EmailPasswordSignUpForm?: ComponentOverride<typeof SignUpForm>; EmailPasswordSignUpHeader?: ComponentOverride<typeof SignUpHeader>; EmailPasswordResetPasswordEmail?: ComponentOverride<typeof ResetPasswordEmail>; EmailPasswordSubmitNewPassword?: ComponentOverride<typeof SubmitNewPassword>; }; export type UserInput = { signInAndUpFeature?: SignInAndUpFeatureUserInput; resetPasswordUsingTokenFeature?: ResetPasswordUsingTokenUserInput; override?: { functions?: ( originalImplementation: RecipeInterface, builder?: OverrideableBuilder<RecipeInterface> ) => RecipeInterface; components?: ComponentOverrideMap; } & AuthRecipeUserInputOverride; } & AuthRecipeModuleUserInput<GetRedirectionURLContext, PreAPIHookContext, OnHandleEventContext>; export type Config = UserInput & AuthRecipeModuleConfig<GetRedirectionURLContext, PreAPIHookContext, OnHandleEventContext>; export type NormalisedConfig = { signInAndUpFeature: NormalisedSignInAndUpFeatureConfig; resetPasswordUsingTokenFeature: NormalisedResetPasswordUsingTokenFeatureConfig; override: { functions: ( originalImplementation: RecipeInterface, builder?: OverrideableBuilder<RecipeInterface> ) => RecipeInterface; components: ComponentOverrideMap; }; } & NormalisedAuthRecipeModuleConfig<GetRedirectionURLContext, PreAPIHookContext, OnHandleEventContext>; export type SignInAndUpFeatureUserInput = { /* * Disable default implementation with default routes. */ disableDefaultImplementation?: boolean; /* * Should default to Sign up form. */ defaultToSignUp?: boolean; /* * SignUp form config. */ signUpForm?: SignUpFormFeatureUserInput; /* * SignIn form config. */ signInForm?: SignInFormFeatureUserInput; }; export type NormalisedSignInAndUpFeatureConfig = { /* * Disable default implementation with default routes. */ disableDefaultImplementation: boolean; /* * Default to sign up form. */ defaultToSignUp: boolean; /* * SignUp form config. */ signUpForm: NormalisedSignUpFormFeatureConfig; /* * SignIn form config. */ signInForm: NormalisedSignInFormFeatureConfig; }; export type SignUpFormFeatureUserInput = FeatureBaseConfig & { /* * Form fields for SignUp. */ formFields?: FormFieldSignUpConfig[]; /* * Privacy policy link for sign up form. */ privacyPolicyLink?: string; /* * Terms and conditions link for sign up form. */ termsOfServiceLink?: string; }; export type NormalisedSignUpFormFeatureConfig = NormalisedBaseConfig & { /* * Normalised form fields for SignUp. */ formFields: NormalisedFormField[]; /* * Privacy policy link for sign up form. */ privacyPolicyLink?: string; /* * Terms and conditions link for sign up form. */ termsOfServiceLink?: string; }; export type SignInFormFeatureUserInput = FeatureBaseConfig & { /* * Form fields for SignIn. */ formFields?: FormFieldSignInConfig[]; }; export type NormalisedSignInFormFeatureConfig = NormalisedBaseConfig & { /* * Normalised form fields for SignIn. */ formFields: NormalisedFormField[]; }; export type FormFieldSignInConfig = FormFieldBaseConfig; export type FormFieldSignUpConfig = FormField; export type ResetPasswordUsingTokenUserInput = { /* * Disable default implementation with default routes. */ disableDefaultImplementation?: boolean; /* * submitNewPasswordForm config. */ submitNewPasswordForm?: FeatureBaseConfig; /* * enterEmailForm config. */ enterEmailForm?: FeatureBaseConfig; }; export type NormalisedResetPasswordUsingTokenFeatureConfig = { /* * Disable default implementation with default routes. */ disableDefaultImplementation: boolean; /* * Normalised submitNewPasswordForm config. */ submitNewPasswordForm: NormalisedSubmitNewPasswordForm; /* * Normalised enterEmailForm config. */ enterEmailForm: NormalisedEnterEmailForm; }; export type NormalisedSubmitNewPasswordForm = FeatureBaseConfig & { formFields: NormalisedFormField[]; }; export type NormalisedEnterEmailForm = FeatureBaseConfig & { formFields: NormalisedFormField[]; }; /* * Props Types. */ type FormThemeBaseProps = ThemeBaseProps & { /* * Form fields to use in the signin form. */ formFields: FormFieldThemeProps[]; }; export type SignInThemeProps = FormThemeBaseProps & { recipeImplementation: RecipeInterface; config: NormalisedConfig; signUpClicked?: () => void; forgotPasswordClick: () => void; onSuccess: () => void; }; export type SignUpThemeProps = FormThemeBaseProps & { recipeImplementation: RecipeInterface; config: NormalisedConfig; signInClicked?: () => void; onSuccess: () => void; }; export type SignInAndUpThemeProps = { signInForm: SignInThemeProps; signUpForm: SignUpThemeProps; config: NormalisedConfig; }; export type NormalisedFormFieldWithError = NormalisedFormField & { /* * Error message to display to users. */ error?: string; }; export type FormFieldThemeProps = NormalisedFormFieldWithError & { /* * Show Is required (*) next to label */ showIsRequired?: boolean; /* * Autocomplete */ autoComplete?: string; }; export type FormFieldState = FormFieldThemeProps & { /* * Has the value already been submitted to its validator. */ validated: boolean; /* * Input */ ref: RefObject<InputRef>; }; export type InputRef = HTMLInputElement & { /* * Is the current input HTML Element focused. */ isFocused?: boolean; }; export type FormFieldError = { /* * Field id. */ id: string; /* * Error message. */ error: string; }; export type PreAPIHookContext = | AuthRecipeModulePreAPIHookContext | { /* * Pre API Hook action. */ action: | "EMAIL_PASSWORD_SIGN_UP" | "EMAIL_PASSWORD_SIGN_IN" | "SEND_RESET_PASSWORD_EMAIL" | "SUBMIT_NEW_PASSWORD" | "EMAIL_EXISTS"; /* * Request object containing query params, body, headers. */ requestInit: RequestInit; /* * URL */ url: string; }; export type GetRedirectionURLContext = | AuthRecipeModuleGetRedirectionURLContext | { /* * Get Redirection URL Context */ action: "RESET_PASSWORD"; }; export type OnHandleEventContext = | AuthRecipeModuleOnHandleEventContext | { /* * On Handle Event actions */ action: "RESET_PASSWORD_EMAIL_SENT" | "PASSWORD_RESET_SUCCESSFUL"; }; export type ResetPasswordUsingTokenThemeProps = { enterEmailForm: EnterEmailProps; submitNewPasswordForm: SubmitNewPasswordProps | undefined; config: NormalisedConfig; }; export type EnterEmailProps = FormThemeBaseProps & { recipeImplementation: RecipeInterface; config: NormalisedConfig; }; export type SubmitNewPasswordProps = FormThemeBaseProps & { recipeImplementation: RecipeInterface; config: NormalisedConfig; onSignInClicked: () => void; token: string; }; export type EnterEmailState = { /* * Enter Email Status */ status: "READY" | "SENT"; }; export type SubmitNewPasswordState = { /* * Submit New Password Theme Status */ status: "READY" | "SUCCESS"; }; export type FormBaseState = | { formFields: FormFieldState[]; status: "IN_PROGRESS" | "READY" | "LOADING" | "FIELD_ERRORS" | "SUCCESS"; } | { formFields: FormFieldState[]; status: "GENERAL_ERROR"; generalError: string; }; export type FormBaseProps = { header?: JSX.Element; footer?: JSX.Element; formFields: FormFieldThemeProps[]; showLabels: boolean; buttonLabel: string; validateOnBlur?: boolean; onSuccess?: () => void; callAPI: (fields: APIFormField[]) => Promise<FormBaseAPIResponse>; }; export type FormBaseAPIResponse = | { /* * Success. */ status: "OK"; /* * User object. */ user?: User; } | { /* * General Errors. */ status: "GENERAL_ERROR"; /* * Error message. */ message: string; } | { /* * Field validation errors. */ status: "FIELD_ERROR"; /* * Array of Field Id and their corresponding error. */ formFields: FormFieldError[]; }; /* * Add documentMode to document object in order to use to detect if browser is IE. */ declare global { interface Document { documentMode?: any; } } export type SignInAndUpState = { user?: User; }; export type RecipeInterface = { submitNewPassword: (input: { formFields: { id: string; value: string; }[]; token: string; config: NormalisedConfig; }) => Promise< | { status: "OK" | "RESET_PASSWORD_INVALID_TOKEN_ERROR"; } | { status: "FIELD_ERROR"; formFields: { id: string; error: string; }[]; } >; sendPasswordResetEmail: (input: { formFields: { id: string; value: string; }[]; config: NormalisedConfig; }) => Promise< | { status: "OK"; } | { status: "FIELD_ERROR"; formFields: { id: string; error: string; }[]; } >; signUp: (input: { formFields: { id: string; value: string; }[]; config: NormalisedConfig; }) => Promise< | { status: "OK"; user: User; } | { status: "FIELD_ERROR"; formFields: { id: string; error: string; }[]; } >; signIn: (input: { formFields: { id: string; value: string; }[]; config: NormalisedConfig; }) => Promise< | { status: "OK"; user: User; } | { status: "FIELD_ERROR"; formFields: { id: string; error: string; }[]; } | { status: "WRONG_CREDENTIALS_ERROR"; } >; doesEmailExist: (input: { email: string; config: NormalisedConfig }) => Promise<boolean>; };
the_stack
import { ChangeDetectorRef, Component, ViewChild } from "@angular/core"; import { ActivatedRoute, Router } from "@angular/router"; import { GlobalVarsService } from "../../global-vars.service"; import { BackendApiService, NFTBidData, NFTBidEntryResponse, NFTEntryResponse, PostEntryResponse, } from "../../backend-api.service"; import { Title } from "@angular/platform-browser"; import { BsModalService } from "ngx-bootstrap/modal"; import { SwalHelper } from "../../../lib/helpers/swal-helper"; import { RouteNames } from "../../app-routing.module"; import { Location } from "@angular/common"; import * as _ from "lodash"; import { SellNftModalComponent } from "../../sell-nft-modal/sell-nft-modal.component"; import { CloseNftAuctionModalComponent } from "../../close-nft-auction-modal/close-nft-auction-modal.component"; import { Subscription } from "rxjs"; import { AddUnlockableModalComponent } from "../../add-unlockable-modal/add-unlockable-modal.component"; import { FeedPostComponent } from "../../feed/feed-post/feed-post.component"; import { environment } from "src/environments/environment"; @Component({ selector: "nft-post", templateUrl: "./nft-post.component.html", styleUrls: ["./nft-post.component.scss"], }) export class NftPostComponent { @ViewChild(FeedPostComponent) feedPost: FeedPostComponent; nftPost: PostEntryResponse; nftPostHashHex: string; nftBidData: NFTBidData; myBids: NFTBidEntryResponse[]; availableSerialNumbers: NFTEntryResponse[]; myAvailableSerialNumbers: NFTEntryResponse[]; loading = true; refreshingBids = true; sellNFTDisabled = true; showPlaceABid: boolean; highBid: number; lowBid: number; selectedBids: boolean[]; selectedBid: NFTBidEntryResponse; showBidsView: boolean = true; bids: NFTBidEntryResponse[]; owners: NFTEntryResponse[]; NftPostComponent = NftPostComponent; activeTab = NftPostComponent.THREAD; static ALL_BIDS = "All Bids"; static MY_BIDS = "My Bids"; static MY_AUCTIONS = "My Auctions"; static OWNERS = "Owners"; static THREAD = "Thread"; tabs = [ NftPostComponent.THREAD, NftPostComponent.ALL_BIDS, NftPostComponent.MY_BIDS, NftPostComponent.MY_AUCTIONS, NftPostComponent.OWNERS, ]; constructor( private route: ActivatedRoute, private router: Router, public globalVars: GlobalVarsService, private backendApi: BackendApiService, private changeRef: ChangeDetectorRef, private modalService: BsModalService, private titleService: Title, private location: Location ) { // This line forces the component to reload when only a url param changes. Without this, the UiScroll component // behaves strangely and can reuse data from a previous post. this.router.routeReuseStrategy.shouldReuseRoute = () => false; this.route.params.subscribe((params) => { this._setStateFromActivatedRoute(route); }); } getPost(fetchParents: boolean = true) { // Hit the Get Single Post endpoint with specific parameters let readerPubKey = ""; if (this.globalVars.loggedInUser) { readerPubKey = this.globalVars.loggedInUser.PublicKeyBase58Check; } return this.backendApi.GetSinglePost( this.globalVars.localNode, this.nftPostHashHex /*PostHashHex*/, readerPubKey /*ReaderPublicKeyBase58Check*/, fetchParents, 0, 0, this.globalVars.showAdminTools() /*AddGlobalFeedBool*/ ); } refreshPosts() { this.loading = true; // Fetch the post entry this.getPost().subscribe( (res) => { if (!res || !res.PostFound) { this.router.navigateByUrl("/" + this.globalVars.RouteNames.NOT_FOUND, { skipLocationChange: true }); return; } if (!res.PostFound.IsNFT) { const postHashHex = res.PostFound.PostHashHex; SwalHelper.fire({ target: this.globalVars.getTargetComponentSelector(), html: "This post is not an NFT", showConfirmButton: true, showCancelButton: true, customClass: { confirmButton: "btn btn-light", cancelButton: "btn btn-light no", }, confirmButtonText: "View Post", cancelButtonText: "Go back", reverseButtons: true, }).then((res) => { if (res.isConfirmed) { this.router.navigate(["/" + RouteNames.POSTS + "/" + postHashHex]); return; } this.location.back(); }); return; } // Set current post this.nftPost = res.PostFound; this.titleService.setTitle(this.nftPost.ProfileEntryResponse.Username + ` on ${environment.node.name}`); this.refreshBidData(); }, (err) => { // TODO: post threads: rollbar console.error(err); this.router.navigateByUrl("/" + this.globalVars.RouteNames.NOT_FOUND, { skipLocationChange: true }); this.loading = false; } ); } refreshBidData(): Subscription { this.refreshingBids = true; return this.backendApi .GetNFTBidsForNFTPost( this.globalVars.localNode, this.globalVars.loggedInUser?.PublicKeyBase58Check, this.nftPost.PostHashHex ) .subscribe( (res) => { this.nftBidData = res; if (!this.nftBidData.BidEntryResponses) { this.nftBidData.BidEntryResponses = []; } if (!this.nftBidData.NFTEntryResponses) { this.nftBidData.NFTEntryResponses = []; } this.availableSerialNumbers = this.nftBidData.NFTEntryResponses.filter( (nftEntryResponse) => nftEntryResponse.IsForSale ); this.myAvailableSerialNumbers = this.availableSerialNumbers.filter( (nftEntryResponse) => nftEntryResponse.OwnerPublicKeyBase58Check === this.globalVars.loggedInUser?.PublicKeyBase58Check ); if (!this.myAvailableSerialNumbers.length) { this.tabs = this.tabs.filter((t) => t !== NftPostComponent.MY_AUCTIONS); this.activeTab = this.activeTab === NftPostComponent.MY_AUCTIONS ? this.tabs[0] : this.activeTab; } this.myBids = this.nftBidData.BidEntryResponses.filter( (bidEntry) => bidEntry.PublicKeyBase58Check === this.globalVars.loggedInUser?.PublicKeyBase58Check ); if (!this.myBids.length) { this.tabs = this.tabs.filter((t) => t !== NftPostComponent.MY_BIDS); this.activeTab = this.activeTab === NftPostComponent.MY_BIDS ? this.tabs[0] : this.activeTab; } this.showPlaceABid = !!(this.availableSerialNumbers.length - this.myAvailableSerialNumbers.length); this.highBid = _.maxBy(this.nftBidData.NFTEntryResponses, "HighestBidAmountNanos").HighestBidAmountNanos; this.lowBid = _.minBy(this.nftBidData.NFTEntryResponses, "LowestBidAmountNanos").LowestBidAmountNanos; this.owners = this.nftBidData.NFTEntryResponses; }, (err) => { console.error(err); this.globalVars._alertError(err); } ) .add(() => { this._handleTabClick(this.activeTab); this.loading = false; this.refreshingBids = false; }); } _setStateFromActivatedRoute(route) { if (this.nftPostHashHex !== route.snapshot.params.postHashHex) { // get the username of the target user (user whose followers / following we're obtaining) this.nftPostHashHex = route.snapshot.params.postHashHex; // it's important that we call this here and not in ngOnInit. Angular does not reload components when only a param changes. // We are responsible for refreshing the components. // if the user is on a thread page and clicks on a comment, the nftPostHashHex will change, but angular won't "load a new // page" and re-render the whole component using the new post hash. instead, angular will // continue using the current component and merely change the URL. so we need to explictly // refresh the posts every time the route changes. this.loading = true; this.refreshPosts(); } } isPostBlocked(post: any): boolean { return this.globalVars.hasUserBlockedCreator(post.PosterPublicKeyBase58Check); } afterUserBlocked(blockedPubKey: any) { this.globalVars.loggedInUser.BlockedPubKeys[blockedPubKey] = {}; } afterNftBidPlaced() { this.loading = true; this.refreshBidData(); } sellNFT(): void { if (this.sellNFTDisabled) { return; } const sellNFTModalDetails = this.modalService.show(SellNftModalComponent, { class: "modal-dialog-center", initialState: { post: this.nftPost, nftEntries: this.nftBidData.NFTEntryResponses, selectedBidEntries: this.nftBidData.BidEntryResponses.filter((bidEntry) => bidEntry.selected), }, }); const onHiddenEvent = sellNFTModalDetails.onHidden; onHiddenEvent.subscribe((response) => { if (response === "nft sold") { this.loading = true; this.refreshPosts(); this.feedPost.getNFTEntries(); } else if (response === "unlockable content opened") { const unlockableModalDetails = this.modalService.show(AddUnlockableModalComponent, { class: "modal-dialog-centered", initialState: { post: this.nftPost, selectedBidEntries: this.nftBidData.BidEntryResponses.filter((bidEntry) => bidEntry.selected), }, }); const onHiddenEvent = unlockableModalDetails.onHidden; onHiddenEvent.subscribe((response) => { if (response === "nft sold") { this.loading = true; this.refreshPosts(); this.feedPost.getNFTEntries(); } }); } }); } checkSelectedBidEntries(bidEntry: NFTBidEntryResponse): void { if (bidEntry.selected) { // De-select any bid entries for the same serial number. this.nftBidData.BidEntryResponses.forEach((bidEntryResponse) => { if ( bidEntryResponse.SerialNumber === bidEntry.SerialNumber && bidEntry !== bidEntryResponse && bidEntryResponse.selected ) { bidEntryResponse.selected = false; } }); } // enabled / disable the Sell NFT button based on the count of bid entries that are selected. this.sellNFTDisabled = !this.nftBidData.BidEntryResponses.filter((bidEntryResponse) => bidEntryResponse.selected) ?.length; } selectBidEntry(bidEntry: NFTBidEntryResponse): void { this.bids.forEach((bidEntry) => (bidEntry.selected = false)); bidEntry.selected = true; this.sellNFTDisabled = false; } closeAuction(): void { const closeNftAuctionModalDetails = this.modalService.show(CloseNftAuctionModalComponent, { class: "modal-dialog-centered", initialState: { post: this.nftPost, myAvailableSerialNumbers: this.myAvailableSerialNumbers, }, }); const onHiddenEvent = closeNftAuctionModalDetails.onHidden; onHiddenEvent.subscribe((response) => { if (response === "auction cancelled") { this.refreshBidData(); this.feedPost.getNFTEntries(); } }); } userOwnsSerialNumber(serialNumber: number): boolean { const loggedInPubKey = this.globalVars.loggedInUser.PublicKeyBase58Check; return !!this.nftBidData.NFTEntryResponses.filter( (nftEntryResponse) => nftEntryResponse.SerialNumber === serialNumber && nftEntryResponse.OwnerPublicKeyBase58Check === loggedInPubKey ).length; } _handleTabClick(tabName: string): void { this.activeTab = tabName; this.showBidsView = tabName === NftPostComponent.ALL_BIDS || tabName === NftPostComponent.MY_BIDS || tabName === NftPostComponent.MY_AUCTIONS; if (this.activeTab === NftPostComponent.ALL_BIDS) { this.bids = this.nftBidData.BidEntryResponses.filter( (bidEntry) => bidEntry.BidAmountNanos <= bidEntry.BidderBalanceNanos ); } else if (this.activeTab === NftPostComponent.MY_BIDS) { this.bids = this.nftBidData.BidEntryResponses.filter( (bidEntry) => bidEntry.PublicKeyBase58Check === this.globalVars.loggedInUser?.PublicKeyBase58Check ); } else if (this.activeTab === NftPostComponent.MY_AUCTIONS) { const serialNumbers = this.myAvailableSerialNumbers?.map((nftEntryResponse) => nftEntryResponse.SerialNumber); this.bids = this.nftBidData.BidEntryResponses.filter( (bidEntry) => (serialNumbers.includes(bidEntry.SerialNumber) || bidEntry.SerialNumber === 0) && bidEntry.BidAmountNanos <= bidEntry.BidderBalanceNanos ); } if (this.showBidsView) { this.sortBids(this.sortByField, this.sortDescending); } else if (this.activeTab === NftPostComponent.OWNERS) { this.sortNftEntries(this.sortByField, this.sortDescending); } } static SORT_BY_PRICE = "PRICE"; static SORT_BY_USERNAME = "USERNAME"; static SORT_BY_EDITION = "EDITION"; sortByField = NftPostComponent.SORT_BY_PRICE; sortDescending = true; sortBids(attribute: string = NftPostComponent.SORT_BY_PRICE, descending: boolean = true): void { if (!this.bids?.length) { return; } const sortDescending = descending ? -1 : 1; this.bids.sort((a, b) => { const bidDiff = this.compareBidAmount(a, b); const serialNumDiff = this.compareSerialNumber(a, b); const usernameDiff = this.compareUsername(a, b); if (attribute === NftPostComponent.SORT_BY_PRICE) { return sortDescending * bidDiff || serialNumDiff || usernameDiff; } else if (attribute === NftPostComponent.SORT_BY_USERNAME) { return sortDescending * usernameDiff || bidDiff || serialNumDiff; } else if (attribute === NftPostComponent.SORT_BY_EDITION) { return sortDescending * serialNumDiff || bidDiff || usernameDiff; } }); } handleColumnHeaderClick(header: string): void { if (this.sortByField === header) { this.sortDescending = !this.sortDescending; } else { this.sortDescending = false; } this.sortByField = header; this.sortBids(header, this.sortDescending); this.sortNftEntries(header, this.sortDescending); } compareBidAmount(a: NFTBidEntryResponse, b: NFTBidEntryResponse): number { return a.BidAmountNanos - b.BidAmountNanos; } compareSerialNumber(a: NFTBidEntryResponse | NFTEntryResponse, b: NFTBidEntryResponse | NFTEntryResponse): number { return a.SerialNumber - b.SerialNumber; } compareUsername(a: NFTBidEntryResponse, b: NFTBidEntryResponse): number { const aUsername = a.ProfileEntryResponse?.Username || a.PublicKeyBase58Check; const bUsername = b.ProfileEntryResponse?.Username || b.PublicKeyBase58Check; if (aUsername < bUsername) { return -1; } if (bUsername < aUsername) { return 1; } return 0; } sortNftEntries(attribute: string, descending: boolean = true): void { if (!this.owners?.length) { return; } const sortDescending = descending ? -1 : 1; this.owners.sort((a, b) => { const lastAcceptedBidDiff = this.compareLastAcceptedBidAmount(a, b); const serialNumDiff = this.compareSerialNumber(a, b); const usernameDiff = this.compareNFTEntryUsername(a, b); if (attribute === NftPostComponent.SORT_BY_PRICE) { return sortDescending * lastAcceptedBidDiff || serialNumDiff || usernameDiff; } else if (attribute === NftPostComponent.SORT_BY_USERNAME) { return sortDescending * usernameDiff || lastAcceptedBidDiff || serialNumDiff; } else if (attribute === NftPostComponent.SORT_BY_EDITION) { return sortDescending * serialNumDiff || lastAcceptedBidDiff || usernameDiff; } }); } compareLastAcceptedBidAmount(a: NFTEntryResponse, b: NFTEntryResponse): number { return a.LastAcceptedBidAmountNanos - b.LastAcceptedBidAmountNanos; } compareNFTEntryUsername(a: NFTEntryResponse, b: NFTEntryResponse): number { const aUsername = a.ProfileEntryResponse?.Username || a.OwnerPublicKeyBase58Check; const bUsername = b.ProfileEntryResponse?.Username || b.OwnerPublicKeyBase58Check; if (aUsername < bUsername) { return -1; } if (bUsername < aUsername) { return 1; } return 0; } selectHighestBids(): void { let highestNFTMap: { [k: number]: NFTBidEntryResponse } = {}; this.bids.forEach((bid) => { const highestBid = highestNFTMap[bid.SerialNumber]; if ( (!highestBid || highestBid.BidAmountNanos < bid.BidAmountNanos) && bid.BidderBalanceNanos >= bid.BidAmountNanos ) { highestNFTMap[bid.SerialNumber] = bid; } }); this.bids.forEach((bid) => { const highestBid = highestNFTMap[bid.SerialNumber]; bid.selected = highestBid.PublicKeyBase58Check === bid.PublicKeyBase58Check && highestBid.BidAmountNanos === bid.BidAmountNanos && highestBid.SerialNumber === bid.SerialNumber; if (this.nftPost.NumNFTCopies === 1 && bid.selected) { this.selectedBid = highestBid; } }); this.sellNFTDisabled = false; } cancelBid(bidEntry: NFTBidEntryResponse): void { SwalHelper.fire({ target: this.globalVars.getTargetComponentSelector(), title: "Cancel Bid", html: `Are you sure you'd like to cancel this bid?`, showCancelButton: true, customClass: { confirmButton: "btn btn-light", cancelButton: "btn btn-light no", }, reverseButtons: true, }).then((res) => { if (res.isConfirmed) { this.backendApi .CreateNFTBid( this.globalVars.localNode, this.globalVars.loggedInUser.PublicKeyBase58Check, this.nftPost.PostHashHex, bidEntry.SerialNumber, 0, this.globalVars.defaultFeeRateNanosPerKB ) .subscribe( (res) => { this.refreshBidData(); }, (err) => { console.error(err); } ); } }); } reloadingThread = false; incrementCommentCounter(): void { this.nftPost.CommentCount += 1; setTimeout(() => (this.reloadingThread = true)); setTimeout(() => (this.reloadingThread = false)); } }
the_stack
import { TestBed, waitForAsync } from "@angular/core/testing"; import { By } from "@angular/platform-browser"; import { Component } from "@angular/core"; import { DISABLE_NATIVE_VALIDITY_CHECKING, MdlTextFieldComponent, } from "./mdl-textfield.component"; import { MdlButtonComponent } from "../button/mdl-button.component"; import { FormsModule } from "@angular/forms"; import { MdlTextFieldModule } from "./mdl-textfield.module"; import { MdlButtonModule } from "../button/mdl-button.module"; @Component({ // eslint-disable-next-line selector: 'test', template: "replaced by the test", }) class MdlTestComponent { public text1 = ""; public numberValue = 0; // eslint-disable-next-line @typescript-eslint/no-empty-function,@typescript-eslint/no-unused-vars public onBlur(event: FocusEvent) {} // eslint-disable-next-line @typescript-eslint/no-empty-function,@typescript-eslint/no-unused-vars public onFocus(event: FocusEvent) {} // eslint-disable-next-line @typescript-eslint/no-empty-function,@typescript-eslint/no-unused-vars public onKeyup(event: KeyboardEvent) {} } describe("Component: MdlTextField", () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [MdlTextFieldModule.forRoot(), MdlButtonModule, FormsModule], declarations: [MdlTestComponent], }); }); it("should add the css class mdl-textfield to the host element", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." ></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const tfEl: HTMLElement = fixture.nativeElement.children.item(0); expect(tfEl.classList.contains("mdl-textfield")).toBe(true); }); it( "should support ngModel", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." [(ngModel)]="text1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); fixture.whenStable().then(() => { const instance = fixture.componentInstance; const component = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).componentInstance; instance.text1 = "text1"; fixture.detectChanges(); fixture.whenStable().then(() => { expect(component.value).toEqual("text1"); component.value = "text2"; fixture.detectChanges(); expect(instance.text1).toEqual("text2"); }); }); }) ); it("should mark the component as focused and blured", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." [(ngModel)]="text1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const hostEl: HTMLElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).nativeElement; const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; const evt = document.createEvent("HTMLEvents"); evt.initEvent("focus", true, true); inputEl.dispatchEvent(evt); fixture.detectChanges(); expect(hostEl.classList.contains("is-focused")).toBe(true); const evtBlur = document.createEvent("HTMLEvents"); evtBlur.initEvent("blur", true, true); inputEl.dispatchEvent(evtBlur); fixture.detectChanges(); expect(hostEl.classList.contains("is-focused")).toBe(false); }); it( "should mark the component as invalid ngModel (pattern)", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." [(ngModel)]="text1" pattern="a"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const hostEl: HTMLElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).nativeElement; const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; el.value = "b"; fixture.detectChanges(); fixture.whenStable().then(() => { expect(hostEl.classList.contains("is-invalid")).toBe(true); }); }) ); it( "should mark the component as invalid ngModel (min)", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="number" label="Text..." [(ngModel)]="text1" min="2"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const hostEl: HTMLElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).nativeElement; const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; el.value = "1"; fixture.detectChanges(); fixture.whenStable().then(() => { expect(hostEl.classList.contains("is-invalid")).toBe(true); }); }) ); it( "should mark the component as invalid ngModel (max)", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="number" label="Text..." [(ngModel)]="text1" max="1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const hostEl: HTMLElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).nativeElement; const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; el.value = "2"; fixture.detectChanges(); fixture.whenStable().then(() => { expect(hostEl.classList.contains("is-invalid")).toBe(true); }); }) ); it( "should mark the component as invalid ngModel (step)", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="number" label="Text..." [(ngModel)]="text1" min="0" step="1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const hostEl: HTMLElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ).nativeElement; const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; el.value = "0.1"; fixture.detectChanges(); fixture.whenStable().then(() => { expect(hostEl.classList.contains("is-invalid")).toBe(true); }); }) ); it("should create a textarea if row is specified", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." rows="3"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el = fixture.debugElement.query(By.css("textarea")); expect(el).toBeDefined(); }); it("should restrict the line count if maxrows is present", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." rows="3" [maxrows]="1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el = fixture.debugElement.query(By.css("textarea")).nativeElement; el.value = "a"; // eslint-disable-next-line const e = new Event('keydown') as any; e.keyCode = 13; spyOn(e, "preventDefault"); el.dispatchEvent(e); expect(e.preventDefault).toHaveBeenCalled(); }); it("should not restrict the line count if maxrows is -1", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ' <mdl-textfield type="text" label="Text..." rows="3" [maxrows]="-1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el = fixture.debugElement.query(By.css("textarea")).nativeElement; el.value = "a"; // eslint-disable-next-line const e = new Event('keydown') as any; e.keyCode = 13; el.dispatchEvent(e); spyOn(e, "preventDefault"); expect(e.preventDefault).not.toHaveBeenCalled(); }); it("should create an expandable textfield if icon is present", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" icon="search"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el = fixture.debugElement.query(By.directive(MdlTextFieldComponent)) .nativeElement; expect(el.classList.contains("mdl-textfield--expandable")).toBe(true); }); it("should activate the expandable if the icon button is clicked", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" icon="search"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const btnEl = fixture.debugElement.query(By.directive(MdlButtonComponent)) .nativeElement; btnEl.click(); fixture.detectChanges(); const el = fixture.debugElement.query(By.directive(MdlTextFieldComponent)) .nativeElement; expect(el.classList.contains("is-focused")).toBe(true); }); it("should add name and id to the input element if provided", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." id="id-1" name="name-1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.name).toEqual("name-1", "name is not set"); expect(inputEl.id).toEqual("id-1", "id is not set"); }); it("should autogenerate an id that must match the labels for-attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Text..." name="name-1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; const id = inputEl.id; expect(id).toBeDefined(); const labelEl: HTMLLabelElement = fixture.debugElement.query( By.css("label") ).nativeElement; expect(labelEl.htmlFor).toBeDefined(id); }); it("should pass autocomplete through to input", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield type="text" label="Name" autocomplete="name"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.getAttribute("autocomplete")).toBe( "name", "The autocomplete attribute should pass to the input." ); }); it("should have native validity check", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" pattern="^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$" label="Text..." name="name-1"> </mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; inputEl.value = "this is not a valid email"; fixture.detectChanges(); const el = fixture.debugElement.query(By.directive(MdlTextFieldComponent)) .nativeElement; expect(el.classList.contains("is-invalid")).toBe( true, "textfield should have css is-invalid" ); }); it("should be possible to deactive native checking locally", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield disableNativeValidityChecking type="text" pattern="^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$" label="Text..." name="name-1"> </mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; inputEl.value = "this is not a valid email"; fixture.detectChanges(); const el = fixture.debugElement.query(By.directive(MdlTextFieldComponent)) .nativeElement; expect(el.classList.contains("is-invalid")).toBe( false, "textfield should not have css is-invalid" ); }); describe("globally deactivated native check", () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [MdlTextFieldModule, MdlButtonModule, FormsModule], declarations: [MdlTestComponent], providers: [ { provide: DISABLE_NATIVE_VALIDITY_CHECKING, useValue: true }, ], }); }); it("should be possible to deactive native checking globally", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" pattern="^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$" label="Text..." name="name-1"> </mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; inputEl.value = "this is not a valid email"; fixture.detectChanges(); const el = fixture.debugElement.query(By.directive(MdlTextFieldComponent)) .nativeElement; expect(el.classList.contains("is-invalid")).toBe( false, "textfield should not have css is-invalid" ); }); }); it("shoud support the autofocus attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" autofocus></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.getAttribute("autofocus")).toBe( "", "the autofocus attribute should be set" ); }); it("should emit the blur and focus event", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" (focus)="onFocus($event)" (blur)="onBlur($event)"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const component = fixture.componentInstance; spyOn(component, "onFocus"); spyOn(component, "onBlur"); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; inputEl.dispatchEvent(new Event("focus")); expect(component.onFocus).toHaveBeenCalled(); inputEl.dispatchEvent(new Event("blur")); expect(component.onBlur).toHaveBeenCalled(); }); it("should be possible to set the focus programmatically", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const textFieldDebugElement = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ); const textFieldComonent = textFieldDebugElement.componentInstance; const el = textFieldDebugElement.nativeElement; textFieldComonent.setFocus(); fixture.detectChanges(); expect(el.classList.contains("is-focused")).toBe(true); }); it( "should be possible to disable the textinputfield", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); const cbDebugElem = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ); cbDebugElem.componentInstance.setDisabledState(true); fixture.detectChanges(); const textInputElement: HTMLElement = cbDebugElem.nativeElement; expect(textInputElement.classList.contains("is-disabled")).toBe( true, "should have css is-disabled" ); fixture.whenStable().then(() => { const inputElement: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputElement.getAttribute("disabled")).toBe( "", "the underlaying input element should be disbaled" ); }); }) ); it( "should keep type number if the input field is type number", waitForAsync(() => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="number" [(ngModel)]="numberValue"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); expect(typeof fixture.componentInstance.numberValue).toBe("number"); const tfFieldComp = fixture.debugElement.query( By.directive(MdlTextFieldComponent) ); const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; el.value = "1"; // eslint-disable-next-line tfFieldComp.componentInstance.triggerChange({target: el} as any); fixture.detectChanges(); expect(tfFieldComp.componentInstance.value).toBe(1); expect(typeof tfFieldComp.componentInstance.value).toBe("number"); el.value = ""; // eslint-disable-next-line tfFieldComp.componentInstance.triggerChange({target: el} as any); fixture.detectChanges(); expect(tfFieldComp.componentInstance.value).toBe(null); expect(typeof tfFieldComp.componentInstance.value).toBe("object"); }) ); it("should add the type text to the input field if no type is specified", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: "<mdl-textfield ></mdl-textfield>", }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; expect(el.type).toBe("text"); }); it("should set given tabindex value", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: '<mdl-textfield tabindex="-1"></mdl-textfield>', }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; expect(el.getAttribute("tabindex")).toBe("-1"); }); it("should not set a default tabindex", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: "<mdl-textfield></mdl-textfield>", }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const el: HTMLInputElement = fixture.debugElement.query(By.css("input")) .nativeElement; expect(el.getAttribute("tabindex")).toEqual(null); }); it("shoud support the readonly attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" readonly></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.readOnly).toBe(true, "the readonly attribute should be set"); }); it("shoud support the required attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" [required]="true"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.required).toBe(true, "the required attribute should be set"); }); it("shoud support the floating-label attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" floating-label></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const tfEl = fixture.debugElement.query( By.css(".mdl-textfield--floating-label") ); expect(tfEl).toBeDefined(); }); it("shoud support the maxlength attribute", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" [maxlength]="10"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const inputEl: HTMLInputElement = fixture.debugElement.query( By.css("input") ).nativeElement; expect(inputEl.getAttribute("maxlength")).toBe( "10", "the maxlength attribute should be set" ); }); it("should emit the keyup event", () => { TestBed.overrideComponent(MdlTestComponent, { set: { template: ` <mdl-textfield type="text" (keyup)="onKeyup()"></mdl-textfield>' `, }, }); const fixture = TestBed.createComponent(MdlTestComponent); fixture.detectChanges(); const testComponent = fixture.componentInstance; spyOn(testComponent, "onKeyup"); const debugElement = fixture.debugElement.query(By.css("input")); debugElement.triggerEventHandler("keyup", {}); expect(testComponent.onKeyup).toHaveBeenCalled(); }); });
the_stack
class Vector2 { public x: any; public y: any; /** * The constructor of the class Vector2. * * @param {(Number|Vector2)} x The initial x coordinate value or, if the single argument, a Vector2 object. * @param {Number} y The initial y coordinate value. */ constructor(x, y) { if (arguments.length == 0) { this.x = 0; this.y = 0; } else if (arguments.length == 1) { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } } /** * Clones this vector and returns the clone. * * @returns {Vector2} The clone of this vector. */ clone() { return new Vector2(this.x, this.y); } /** * Returns a string representation of this vector. * * @returns {String} A string representation of this vector. */ toString() { return '(' + this.x + ',' + this.y + ')'; } /** * Add the x and y coordinate values of a vector to the x and y coordinate values of this vector. * * @param {Vector2} vec Another vector. * @returns {Vector2} Returns itself. */ add(vec) { this.x += vec.x; this.y += vec.y; return this; } /** * Subtract the x and y coordinate values of a vector from the x and y coordinate values of this vector. * * @param {Vector2} vec Another vector. * @returns {Vector2} Returns itself. */ subtract(vec) { this.x -= vec.x; this.y -= vec.y; return this; } /** * Divide the x and y coordinate values of this vector by a scalar. * * @param {Number} scalar The scalar. * @returns {Vector2} Returns itself. */ divide(scalar) { this.x /= scalar; this.y /= scalar; return this; } /** * Multiply the x and y coordinate values of this vector by the values of another vector. * * @param {Vector2} v A vector. * @returns {Vector2} Returns itself. */ multiply(v) { this.x *= v.x; this.y *= v.y; return this; } /** * Multiply the x and y coordinate values of this vector by a scalar. * * @param {Number} scalar The scalar. * @returns {Vector2} Returns itself. */ multiplyScalar(scalar) { this.x *= scalar; this.y *= scalar; return this; } /** * Inverts this vector. Same as multiply(-1.0). * * @returns {Vector2} Returns itself. */ invert() { this.x = -this.x; this.y = -this.y; return this; } /** * Returns the angle of this vector in relation to the coordinate system. * * @returns {Number} The angle in radians. */ angle() { return Math.atan2(this.y, this.x); } /** * Returns the euclidean distance between this vector and another vector. * * @param {Vector2} vec A vector. * @returns {Number} The euclidean distance between the two vectors. */ distance(vec) { return Math.sqrt((vec.x - this.x) * (vec.x - this.x) + (vec.y - this.y) * (vec.y - this.y)); } /** * Returns the squared euclidean distance between this vector and another vector. When only the relative distances of a set of vectors are needed, this is is less expensive than using distance(vec). * * @param {Vector2} vec Another vector. * @returns {Number} The squared euclidean distance of the two vectors. */ distanceSq(vec) { return (vec.x - this.x) * (vec.x - this.x) + (vec.y - this.y) * (vec.y - this.y); } /** * Checks whether or not this vector is in a clockwise or counter-clockwise rotational direction compared to another vector in relation to the coordinate system. * * @param {Vector2} vec Another vector. * @returns {Number} Returns -1, 0 or 1 if the vector supplied as an argument is clockwise, neutral or counter-clockwise respectively to this vector in relation to the coordinate system. */ clockwise(vec) { let a = this.y * vec.x; let b = this.x * vec.y; if (a > b) { return -1; } else if (a === b) { return 0; } return 1; } /** * Checks whether or not this vector is in a clockwise or counter-clockwise rotational direction compared to another vector in relation to an arbitrary third vector. * * @param {Vector2} center The central vector. * @param {Vector2} vec Another vector. * @returns {Number} Returns -1, 0 or 1 if the vector supplied as an argument is clockwise, neutral or counter-clockwise respectively to this vector in relation to an arbitrary third vector. */ relativeClockwise(center, vec) { let a = (this.y - center.y) * (vec.x - center.x); let b = (this.x - center.x) * (vec.y - center.y); if (a > b) { return -1; } else if (a === b) { return 0; } return 1; } /** * Rotates this vector by a given number of radians around the origin of the coordinate system. * * @param {Number} angle The angle in radians to rotate the vector. * @returns {Vector2} Returns itself. */ rotate(angle) { let tmp = new Vector2(0, 0); let cosAngle = Math.cos(angle); let sinAngle = Math.sin(angle); tmp.x = this.x * cosAngle - this.y * sinAngle; tmp.y = this.x * sinAngle + this.y * cosAngle; this.x = tmp.x; this.y = tmp.y; return this; } /** * Rotates this vector around another vector. * * @param {Number} angle The angle in radians to rotate the vector. * @param {Vector2} vec The vector which is used as the rotational center. * @returns {Vector2} Returns itself. */ rotateAround(angle, vec) { let s = Math.sin(angle); let c = Math.cos(angle); this.x -= vec.x; this.y -= vec.y; let x = this.x * c - this.y * s; let y = this.x * s + this.y * c; this.x = x + vec.x; this.y = y + vec.y; return this; } /** * Rotate a vector around a given center to the same angle as another vector (so that the two vectors and the center are in a line, with both vectors on one side of the center), keeps the distance from this vector to the center. * * @param {Vector2} vec The vector to rotate this vector to. * @param {Vector2} center The rotational center. * @param {Number} [offsetAngle=0.0] An additional amount of radians to rotate the vector. * @returns {Vector2} Returns itself. */ rotateTo(vec, center, offsetAngle = 0.0) { // Problem if this is first position this.x += 0.001; this.y -= 0.001; let a = Vector2.subtract(this, center); let b = Vector2.subtract(vec, center); let angle = Vector2.angle(b, a); this.rotateAround(angle + offsetAngle, center); return this; } /** * Rotates the vector away from a specified vector around a center. * * @param {Vector2} vec The vector this one is rotated away from. * @param {Vector2} center The rotational center. * @param {Number} angle The angle by which to rotate. */ rotateAwayFrom(vec, center, angle) { this.rotateAround(angle, center); let distSqA = this.distanceSq(vec); this.rotateAround(-2.0 * angle, center); let distSqB = this.distanceSq(vec); // If it was rotated towards the other vertex, rotate in other direction by same amount. if (distSqB < distSqA) { this.rotateAround(2.0 * angle, center); } } /** * Returns the angle in radians used to rotate this vector away from a given vector. * * @param {Vector2} vec The vector this one is rotated away from. * @param {Vector2} center The rotational center. * @param {Number} angle The angle by which to rotate. * @returns {Number} The angle in radians. */ getRotateAwayFromAngle(vec, center, angle) { let tmp = this.clone(); tmp.rotateAround(angle, center); let distSqA = tmp.distanceSq(vec); tmp.rotateAround(-2.0 * angle, center); let distSqB = tmp.distanceSq(vec); if (distSqB < distSqA) { return angle; } else { return -angle; } } /** * Returns the angle in radians used to rotate this vector towards a given vector. * * @param {Vector2} vec The vector this one is rotated towards to. * @param {Vector2} center The rotational center. * @param {Number} angle The angle by which to rotate. * @returns {Number} The angle in radians. */ getRotateTowardsAngle(vec, center, angle) { let tmp = this.clone(); tmp.rotateAround(angle, center); let distSqA = tmp.distanceSq(vec); tmp.rotateAround(-2.0 * angle, center); let distSqB = tmp.distanceSq(vec); if (distSqB > distSqA) { return angle; } else { return -angle; } } /** * Gets the angles between this vector and another vector around a common center of rotation. * * @param {Vector2} vec Another vector. * @param {Vector2} center The center of rotation. * @returns {Number} The angle between this vector and another vector around a center of rotation in radians. */ getRotateToAngle(vec, center) { let a = Vector2.subtract(this, center); let b = Vector2.subtract(vec, center); let angle = Vector2.angle(b, a); return Number.isNaN(angle) ? 0.0 : angle; } /** * Checks whether a vector lies within a polygon spanned by a set of vectors. * * @param {Vector2[]} polygon An array of vectors spanning the polygon. * @returns {Boolean} A boolean indicating whether or not this vector is within a polygon. */ isInPolygon(polygon) { let inside = false; // Its not always a given, that the polygon is convex (-> sugars) for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { if (((polygon[i].y > this.y) != (polygon[j].y > this.y)) && (this.x < (polygon[j].x - polygon[i].x) * (this.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x)) { inside = !inside; } } return inside; } /** * Returns the length of this vector. * * @returns {Number} The length of this vector. */ length() { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } /** * Returns the square of the length of this vector. * * @returns {Number} The square of the length of this vector. */ lengthSq() { return (this.x * this.x) + (this.y * this.y); } /** * Normalizes this vector. * * @returns {Vector2} Returns itself. */ normalize() { this.divide(this.length()); return this; } /** * Returns a normalized copy of this vector. * * @returns {Vector2} A normalized copy of this vector. */ normalized() { return Vector2.divideScalar(this, this.length()); } /** * Calculates which side of a line spanned by two vectors this vector is. * * @param {Vector2} vecA A vector. * @param {Vector2} vecB A vector. * @returns {Number} A number indicating the side of this vector, given a line spanned by two other vectors. */ whichSide(vecA, vecB) { return (this.x - vecA.x) * (vecB.y - vecA.y) - (this.y - vecA.y) * (vecB.x - vecA.x); } /** * Checks whether or not this vector is on the same side of a line spanned by two vectors as another vector. * * @param {Vector2} vecA A vector spanning the line. * @param {Vector2} vecB A vector spanning the line. * @param {Vector2} vecC A vector to check whether or not it is on the same side as this vector. * @returns {Boolean} Returns a boolean indicating whether or not this vector is on the same side as another vector. */ sameSideAs(vecA, vecB, vecC) { let d = this.whichSide(vecA, vecB); let dRef = vecC.whichSide(vecA, vecB); return d < 0 && dRef < 0 || d == 0 && dRef == 0 || d > 0 && dRef > 0; } /** * Adds two vectors and returns the result as a new vector. * * @static * @param {Vector2} vecA A summand. * @param {Vector2} vecB A summand. * @returns {Vector2} Returns the sum of two vectors. */ static add(vecA, vecB) { return new Vector2(vecA.x + vecB.x, vecA.y + vecB.y); } /** * Subtracts one vector from another and returns the result as a new vector. * * @static * @param {Vector2} vecA The minuend. * @param {Vector2} vecB The subtrahend. * @returns {Vector2} Returns the difference of two vectors. */ static subtract(vecA, vecB) { return new Vector2(vecA.x - vecB.x, vecA.y - vecB.y); } /** * Multiplies two vectors (value by value) and returns the result. * * @static * @param {Vector2} vecA A vector. * @param {Vector2} vecB A vector. * @returns {Vector2} Returns the product of two vectors. */ static multiply(vecA, vecB) { return new Vector2(vecA.x * vecB.x, vecA.y * vecB.y); } /** * Multiplies two vectors (value by value) and returns the result. * * @static * @param {Vector2} vec A vector. * @param {Number} scalar A scalar. * @returns {Vector2} Returns the product of two vectors. */ static multiplyScalar(vec, scalar) { return new Vector2(vec.x, vec.y).multiplyScalar(scalar); } /** * Returns the midpoint of a line spanned by two vectors. * * @static * @param {Vector2} vecA A vector spanning the line. * @param {Vector2} vecB A vector spanning the line. * @returns {Vector2} The midpoint of the line spanned by two vectors. */ static midpoint(vecA, vecB) { return new Vector2((vecA.x + vecB.x) / 2, (vecA.y + vecB.y) / 2); } /** * Returns the normals of a line spanned by two vectors. * * @static * @param {Vector2} vecA A vector spanning the line. * @param {Vector2} vecB A vector spanning the line. * @returns {Vector2[]} An array containing the two normals, each represented by a vector. */ static normals(vecA, vecB) { let delta = Vector2.subtract(vecB, vecA); return [ new Vector2(-delta.y, delta.x), new Vector2(delta.y, -delta.x) ]; } /** * Returns the unit (normalized normal) vectors of a line spanned by two vectors. * * @static * @param {Vector2} vecA A vector spanning the line. * @param {Vector2} vecB A vector spanning the line. * @returns {Vector2[]} An array containing the two unit vectors. */ static units(vecA, vecB) { let delta = Vector2.subtract(vecB, vecA); return [ (new Vector2(-delta.y, delta.x)).normalize(), (new Vector2(delta.y, -delta.x)).normalize() ]; } /** * Divides a vector by another vector and returns the result as new vector. * * @static * @param {Vector2} vecA The dividend. * @param {Vector2} vecB The divisor. * @returns {Vector2} The fraction of the two vectors. */ static divide(vecA, vecB) { return new Vector2(vecA.x / vecB.x, vecA.y / vecB.y); } /** * Divides a vector by a scalar and returns the result as new vector. * * @static * @param {Vector2} vecA The dividend. * @param {Number} s The scalar. * @returns {Vector2} The fraction of the two vectors. */ static divideScalar(vecA, s) { return new Vector2(vecA.x / s, vecA.y / s); } /** * Returns the dot product of two vectors. * * @static * @param {Vector2} vecA A vector. * @param {Vector2} vecB A vector. * @returns {Number} The dot product of two vectors. */ static dot(vecA, vecB) { return vecA.x * vecB.x + vecA.y * vecB.y; } /** * Returns the angle between two vectors. * * @static * @param {Vector2} vecA A vector. * @param {Vector2} vecB A vector. * @returns {Number} The angle between two vectors in radians. */ static angle(vecA, vecB) { let dot = Vector2.dot(vecA, vecB); return Math.acos(dot / (vecA.length() * vecB.length())); } /** * Returns the angle between two vectors based on a third vector in between. * * @static * @param {Vector2} vecA A vector. * @param {Vector2} vecB A (central) vector. * @param {Vector2} vecC A vector. * @returns {Number} The angle in radians. */ static threePointangle(vecA, vecB, vecC) { let ab = Vector2.subtract(vecB, vecA); let bc = Vector2.subtract(vecC, vecB); let abLength = vecA.distance(vecB); let bcLength = vecB.distance(vecC); return Math.acos(Vector2.dot(ab, bc) / (abLength * bcLength)); } /** * Returns the scalar projection of a vector on another vector. * * @static * @param {Vector2} vecA The vector to be projected. * @param {Vector2} vecB The vector to be projection upon. * @returns {Number} The scalar component. */ static scalarProjection(vecA, vecB) { let unit = vecB.normalized(); return Vector2.dot(vecA, unit); } /** * Returns the average vector (normalized) of the input vectors. * * @static * @param {Array} vecs An array containing vectors. * @returns {Vector2} The resulting vector (normalized). */ static averageDirection(vecs) { let avg = new Vector2(0.0, 0.0); for (var i = 0; i < vecs.length; i++) { let vec = vecs[i]; avg.add(vec); } return avg.normalize(); } } export default Vector2;
the_stack
import { DefaultPrivacyLevel, monitor, noop } from '@datadog/browser-core' import { getMutationObserverConstructor } from '@datadog/browser-rum-core' import { NodePrivacyLevel } from '../../constants' import { getNodePrivacyLevel, getTextContent } from './privacy' import { getElementInputValue, getSerializedNodeId, hasSerializedNode, nodeAndAncestorsHaveSerializedNode, NodeWithSerializedNode, } from './serializationUtils' import { serializeNodeWithId, serializeAttribute } from './serialize' import { AddedNodeMutation, AttributeMutation, RumAttributesMutationRecord, RumCharacterDataMutationRecord, RumChildListMutationRecord, MutationCallBack, RumMutationRecord, RemovedNodeMutation, TextMutation, } from './types' import { forEach } from './utils' import { createMutationBatch } from './mutationBatch' type WithSerializedTarget<T> = T & { target: NodeWithSerializedNode } /** * Buffers and aggregate mutations generated by a MutationObserver into MutationPayload */ export function startMutationObserver( controller: MutationController, mutationCallback: MutationCallBack, defaultPrivacyLevel: DefaultPrivacyLevel ) { const MutationObserver = getMutationObserverConstructor() if (!MutationObserver) { return { stop: noop } } const mutationBatch = createMutationBatch((mutations) => { processMutations( mutations.concat(observer.takeRecords() as RumMutationRecord[]), mutationCallback, defaultPrivacyLevel ) }) const observer = new MutationObserver(monitor(mutationBatch.addMutations) as (callback: MutationRecord[]) => void) observer.observe(document, { attributeOldValue: true, attributes: true, characterData: true, characterDataOldValue: true, childList: true, subtree: true, }) controller.onFlush(mutationBatch.flush) return { stop: () => { observer.disconnect() mutationBatch.stop() }, } } /** * Controls how mutations are processed, allowing to flush pending mutations. */ export class MutationController { private flushListener?: () => void public flush() { this.flushListener?.() } public onFlush(listener: () => void) { this.flushListener = listener } } function processMutations( mutations: RumMutationRecord[], mutationCallback: MutationCallBack, defaultPrivacyLevel: DefaultPrivacyLevel ) { // Discard any mutation with a 'target' node that: // * isn't injected in the current document or isn't known/serialized yet: those nodes are likely // part of a mutation occurring in a parent Node // * should be hidden or ignored const filteredMutations = mutations.filter( (mutation): mutation is WithSerializedTarget<RumMutationRecord> => document.contains(mutation.target) && nodeAndAncestorsHaveSerializedNode(mutation.target) && getNodePrivacyLevel(mutation.target, defaultPrivacyLevel) !== NodePrivacyLevel.HIDDEN ) const { adds, removes, hasBeenSerialized } = processChildListMutations( filteredMutations.filter( (mutation): mutation is WithSerializedTarget<RumChildListMutationRecord> => mutation.type === 'childList' ), defaultPrivacyLevel ) const texts = processCharacterDataMutations( filteredMutations.filter( (mutation): mutation is WithSerializedTarget<RumCharacterDataMutationRecord> => mutation.type === 'characterData' && !hasBeenSerialized(mutation.target) ), defaultPrivacyLevel ) const attributes = processAttributesMutations( filteredMutations.filter( (mutation): mutation is WithSerializedTarget<RumAttributesMutationRecord> => mutation.type === 'attributes' && !hasBeenSerialized(mutation.target) ), defaultPrivacyLevel ) if (!texts.length && !attributes.length && !removes.length && !adds.length) { return } mutationCallback({ adds, removes, texts, attributes, }) } function processChildListMutations( mutations: Array<WithSerializedTarget<RumChildListMutationRecord>>, defaultPrivacyLevel: DefaultPrivacyLevel ) { // First, we iterate over mutations to collect: // // * nodes that have been added in the document and not removed by a subsequent mutation // * nodes that have been removed from the document but were not added in a previous mutation // // For this second category, we also collect their previous parent (mutation.target) because we'll // need it to emit a 'remove' mutation. // // Those two categories may overlap: if a node moved from a position to another, it is reported as // two mutation records, one with a "removedNodes" and the other with "addedNodes". In this case, // the node will be in both sets. const addedAndMovedNodes = new Set<Node>() const removedNodes = new Map<Node, NodeWithSerializedNode>() for (const mutation of mutations) { forEach(mutation.addedNodes, (node) => { addedAndMovedNodes.add(node) }) forEach(mutation.removedNodes, (node) => { if (!addedAndMovedNodes.has(node)) { removedNodes.set(node, mutation.target) } addedAndMovedNodes.delete(node) }) } // Then, we sort nodes that are still in the document by topological order, for two reasons: // // * We will serialize each added nodes with their descendants. We don't want to serialize a node // twice, so we need to iterate over the parent nodes first and skip any node that is contained in // a precedent node. // // * To emit "add" mutations, we need references to the parent and potential next sibling of each // added node. So we need to iterate over the parent nodes first, and when multiple nodes are // siblings, we want to iterate from last to first. This will ensure that any "next" node is // already serialized and have an id. const sortedAddedAndMovedNodes = Array.from(addedAndMovedNodes) sortAddedAndMovedNodes(sortedAddedAndMovedNodes) // Then, we iterate over our sorted node sets to emit mutations. We collect the newly serialized // node ids in a set to be able to skip subsequent related mutations. const serializedNodeIds = new Set<number>() const addedNodeMutations: AddedNodeMutation[] = [] for (const node of sortedAddedAndMovedNodes) { if (hasBeenSerialized(node)) { continue } const parentNodePrivacyLevel = getNodePrivacyLevel(node.parentNode!, defaultPrivacyLevel) if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) { continue } const serializedNode = serializeNodeWithId(node, { document, serializedNodeIds, parentNodePrivacyLevel, }) if (!serializedNode) { continue } addedNodeMutations.push({ nextId: getNextSibling(node), parentId: getSerializedNodeId(node.parentNode!)!, node: serializedNode, }) } // Finally, we emit remove mutations. const removedNodeMutations: RemovedNodeMutation[] = [] removedNodes.forEach((parent, node) => { if (hasSerializedNode(node)) { removedNodeMutations.push({ parentId: getSerializedNodeId(parent), id: getSerializedNodeId(node), }) } }) return { adds: addedNodeMutations, removes: removedNodeMutations, hasBeenSerialized } function hasBeenSerialized(node: Node) { return hasSerializedNode(node) && serializedNodeIds.has(getSerializedNodeId(node)) } function getNextSibling(node: Node): null | number { let nextSibling = node.nextSibling while (nextSibling) { if (hasSerializedNode(nextSibling)) { return getSerializedNodeId(nextSibling) } nextSibling = nextSibling.nextSibling } return null } } function processCharacterDataMutations( mutations: Array<WithSerializedTarget<RumCharacterDataMutationRecord>>, defaultPrivacyLevel: DefaultPrivacyLevel ) { const textMutations: TextMutation[] = [] // Deduplicate mutations based on their target node const handledNodes = new Set<Node>() const filteredMutations = mutations.filter((mutation) => { if (handledNodes.has(mutation.target)) { return false } handledNodes.add(mutation.target) return true }) // Emit mutations for (const mutation of filteredMutations) { const value = mutation.target.textContent if (value === mutation.oldValue) { continue } const parentNodePrivacyLevel = getNodePrivacyLevel(mutation.target.parentNode!, defaultPrivacyLevel) if (parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN || parentNodePrivacyLevel === NodePrivacyLevel.IGNORE) { continue } textMutations.push({ id: getSerializedNodeId(mutation.target), // TODO: pass a valid "ignoreWhiteSpace" argument value: getTextContent(mutation.target, false, parentNodePrivacyLevel) ?? null, }) } return textMutations } function processAttributesMutations( mutations: Array<WithSerializedTarget<RumAttributesMutationRecord>>, defaultPrivacyLevel: DefaultPrivacyLevel ) { const attributeMutations: AttributeMutation[] = [] // Deduplicate mutations based on their target node and changed attribute const handledElements = new Map<Element, Set<string>>() const filteredMutations = mutations.filter((mutation) => { const handledAttributes = handledElements.get(mutation.target) if (handledAttributes?.has(mutation.attributeName!)) { return false } if (!handledAttributes) { handledElements.set(mutation.target, new Set([mutation.attributeName!])) } else { handledAttributes.add(mutation.attributeName!) } return true }) // Emit mutations const emittedMutations = new Map<Element, AttributeMutation>() for (const mutation of filteredMutations) { const uncensoredValue = mutation.target.getAttribute(mutation.attributeName!) if (uncensoredValue === mutation.oldValue) { continue } const privacyLevel = getNodePrivacyLevel(mutation.target, defaultPrivacyLevel) const attributeValue = serializeAttribute(mutation.target, privacyLevel, mutation.attributeName!) let transformedValue: string | null if (mutation.attributeName === 'value') { const inputValue = getElementInputValue(mutation.target, privacyLevel) if (inputValue === undefined) { continue } transformedValue = inputValue } else if (attributeValue && typeof attributeValue === 'string') { transformedValue = attributeValue } else { transformedValue = null } let emittedMutation = emittedMutations.get(mutation.target) if (!emittedMutation) { emittedMutation = { id: getSerializedNodeId(mutation.target), attributes: {}, } attributeMutations.push(emittedMutation) emittedMutations.set(mutation.target, emittedMutation) } emittedMutation.attributes[mutation.attributeName!] = transformedValue } return attributeMutations } export function sortAddedAndMovedNodes(nodes: Node[]) { nodes.sort((a, b) => { const position = a.compareDocumentPosition(b) /* eslint-disable no-bitwise */ if (position & Node.DOCUMENT_POSITION_CONTAINED_BY) { return -1 } else if (position & Node.DOCUMENT_POSITION_CONTAINS) { return 1 } else if (position & Node.DOCUMENT_POSITION_FOLLOWING) { return 1 } else if (position & Node.DOCUMENT_POSITION_PRECEDING) { return -1 } /* eslint-enable no-bitwise */ return 0 }) }
the_stack
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { CourseWideContext, PostSortCriterion, SortDirection } from 'app/shared/metis/metis.util'; import { PostingThreadComponent } from 'app/shared/metis/posting-thread/posting-thread.component'; import { PostCreateEditModalComponent } from 'app/shared/metis/posting-create-edit-modal/post-create-edit-modal/post-create-edit-modal.component'; import { ButtonComponent } from 'app/shared/components/button.component'; import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { HttpResponse } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { getElement } from '../../../helpers/utils/general.utils'; import { NgbPaginationModule, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { MockComponent, MockDirective, MockModule, MockPipe, MockProvider } from 'ng-mocks'; import { Course } from 'app/entities/course.model'; import { CourseManagementService } from 'app/course/manage/course-management.service'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { MetisService } from 'app/shared/metis/metis.service'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; import { MockExerciseService } from '../../../helpers/mocks/service/mock-exercise.service'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { AnswerPostService } from 'app/shared/metis/answer-post.service'; import { MockAnswerPostService } from '../../../helpers/mocks/service/mock-answer-post.service'; import { PostService } from 'app/shared/metis/post.service'; import { MockPostService } from '../../../helpers/mocks/service/mock-post.service'; import { CourseDiscussionComponent } from 'app/overview/course-discussion/course-discussion.component'; import { TranslateService } from '@ngx-translate/core'; import { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service'; import { MockRouter } from '../../../helpers/mocks/mock-router'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { MockLocalStorageService } from '../../../helpers/mocks/service/mock-local-storage.service'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { ItemCountComponent } from 'app/shared/pagination/item-count.component'; import { metisCourse, metisCoursePosts, metisCoursePostsWithCourseWideContext, metisExercise, metisExercise2, metisExercisePosts, metisLecture, metisLecture2, metisLecturePosts, metisUser1, } from '../../../helpers/sample/metis-sample-data'; describe('CourseDiscussionComponent', () => { let component: CourseDiscussionComponent; let fixture: ComponentFixture<CourseDiscussionComponent>; let courseManagementService: CourseManagementService; let metisService: MetisService; let metisServiceGetFilteredPostsSpy: jest.SpyInstance; let metisServiceGetUserStub: jest.SpyInstance; const id = metisCourse.id; const parentRoute = { parent: { params: of({ id }), queryParams: of({ searchText: '' }), }, } as any as ActivatedRoute; const route = { parent: parentRoute } as any as ActivatedRoute; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, MockModule(FormsModule), MockModule(ReactiveFormsModule), MockModule(NgbPaginationModule)], declarations: [ CourseDiscussionComponent, MockComponent(PostingThreadComponent), MockComponent(PostCreateEditModalComponent), MockComponent(FaIconComponent), MockPipe(ArtemisTranslatePipe), MockDirective(NgbTooltip), MockComponent(ButtonComponent), MockComponent(ItemCountComponent), ], providers: [ FormBuilder, MockProvider(SessionStorageService), { provide: ExerciseService, useClass: MockExerciseService }, { provide: AnswerPostService, useClass: MockAnswerPostService }, { provide: PostService, useClass: MockPostService }, { provide: ActivatedRoute, useValue: route }, { provide: TranslateService, useClass: MockTranslateService }, { provide: Router, useClass: MockRouter }, { provide: LocalStorageService, useClass: MockLocalStorageService }, { provide: MetisService, useClass: MetisService }, ], }) .compileComponents() .then(() => { courseManagementService = TestBed.inject(CourseManagementService); jest.spyOn(courseManagementService, 'findOneForDashboard').mockReturnValue(of({ body: metisCourse }) as Observable<HttpResponse<Course>>); fixture = TestBed.createComponent(CourseDiscussionComponent); component = fixture.componentInstance; metisService = fixture.debugElement.injector.get(MetisService); metisServiceGetFilteredPostsSpy = jest.spyOn(metisService, 'getFilteredPosts'); metisServiceGetUserStub = jest.spyOn(metisService, 'getUser'); }); }); afterEach(() => { jest.restoreAllMocks(); }); it('should set course and posts for course on initialization', fakeAsync(() => { component.ngOnInit(); tick(); expect(component.course).toBe(metisCourse); expect(component.createdPost).not.toBe(null); expect(component.posts).toEqual(metisCoursePosts); expect(component.currentPostContextFilter).toEqual({ courseId: metisCourse.id, courseWideContext: undefined, exerciseId: undefined, lectureId: undefined, searchText: undefined, filterToUnresolved: false, filterToOwn: false, filterToAnsweredOrReacted: false, postSortCriterion: PostSortCriterion.CREATION_DATE, sortingOrder: SortDirection.DESCENDING, }); })); it('should initialize formGroup correctly', fakeAsync(() => { component.ngOnInit(); tick(); expect(component.formGroup.get('context')?.value).toEqual({ courseId: metisCourse.id, courseWideContext: undefined, exerciseId: undefined, lectureId: undefined, searchText: undefined, filterToUnresolved: false, filterToOwn: false, filterToAnsweredOrReacted: false, postSortCriterion: PostSortCriterion.CREATION_DATE, sortingOrder: SortDirection.DESCENDING, }); expect(component.formGroup.get('sortBy')?.value).toBe(PostSortCriterion.CREATION_DATE); expect(component.formGroup.get('filterToUnresolved')?.value).toBeFalse(); expect(component.formGroup.get('filterToOwn')?.value).toBeFalse(); expect(component.formGroup.get('filterToAnsweredOrReacted')?.value).toBeFalse(); })); it('should initialize overview page with course posts for default settings correctly', fakeAsync(() => { component.ngOnInit(); tick(); expect(component.formGroup.get('context')?.value).toEqual({ courseId: metisCourse.id, courseWideContext: undefined, exerciseId: undefined, lectureId: undefined, searchText: undefined, filterToUnresolved: false, filterToOwn: false, filterToAnsweredOrReacted: false, postSortCriterion: PostSortCriterion.CREATION_DATE, sortingOrder: SortDirection.DESCENDING, }); expect(component.formGroup.get('sortBy')?.value).toEqual(PostSortCriterion.CREATION_DATE); expect(component.currentSortDirection).toBe(SortDirection.DESCENDING); fixture.detectChanges(); const searchInput = getElement(fixture.debugElement, 'input[name=searchText]'); expect(searchInput.textContent).toBe(''); const contextOptions = getElement(fixture.debugElement, 'select[name=context]'); expect(component.lectures).toEqual([metisLecture, metisLecture2]); expect(component.exercises).toEqual([metisExercise, metisExercise2]); // select should provide all context options expect(contextOptions.textContent).toContain(metisCourse.title); expect(contextOptions.textContent).toContain(metisLecture.title); expect(contextOptions.textContent).toContain(metisLecture2.title); expect(contextOptions.textContent).toContain(metisExercise.title); expect(contextOptions.textContent).toContain(metisExercise2.title); // course should be selected const selectedContextOption = getElement(fixture.debugElement, 'select[name=context]'); expect(selectedContextOption.value).toContain(metisCourse.title); // creation date should be selected as sort criterion const selectedSortByOption = getElement(fixture.debugElement, 'select[name=sortBy]'); expect(selectedSortByOption.value).not.toBeNull(); // descending should be selected as sort direction // show correct number of posts found const postCountInformation = getElement(fixture.debugElement, '.post-result-information'); expect(component.posts).toEqual(metisCoursePosts); expect(postCountInformation.textContent).not.toBeNull(); })); it('should invoke metis service forcing a reload from server when search text changed', fakeAsync(() => { component.ngOnInit(); tick(); component.searchText = 'textToSearch'; component.onSelectContext(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledWith({ courseId: metisCourse.id, courseWideContext: undefined, exerciseId: undefined, lectureId: undefined, searchText: component.searchText, filterToUnresolved: false, filterToOwn: false, filterToAnsweredOrReacted: false, page: component.page - 1, pageSize: component.itemsPerPage, pagingEnabled: true, postSortCriterion: 'CREATION_DATE', sortingOrder: 'DESCENDING', }); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(2); })); it('should invoke metis service and update filter setting when filterToUnresolved checkbox is checked', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ filterToUnresolved: true, filterToOwn: false, filterToAnsweredOrReacted: false, }); const filterResolvedCheckbox = getElement(fixture.debugElement, 'input[name=filterToUnresolved]'); filterResolvedCheckbox.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(component.currentPostContextFilter.filterToUnresolved).toBeTrue(); // actual post filtering done at server side, tested by AnswerPostIntegrationTest })); it('should invoke metis service and update filter setting when filterToUnresolved and filterToOwn checkbox is checked', fakeAsync(() => { const currentUser = metisUser1; metisServiceGetUserStub.mockReturnValue(currentUser); component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ filterToUnresolved: true, filterToOwn: true, filterToAnsweredOrReacted: false, }); const filterResolvedCheckbox = getElement(fixture.debugElement, 'input[name=filterToUnresolved]'); const filterOwnCheckbox = getElement(fixture.debugElement, 'input[name=filterToOwn]'); filterResolvedCheckbox.dispatchEvent(new Event('change')); filterOwnCheckbox.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(4); expect(component.currentPostContextFilter.filterToUnresolved).toBeTrue(); expect(component.currentPostContextFilter.filterToOwn).toBeTrue(); expect(component.currentPostContextFilter.filterToAnsweredOrReacted).toBeFalse(); // actual post filtering done at server side, tested by AnswerPostIntegrationTest })); it('should invoke metis service and update filter setting when filterToOwn checkbox is checked', fakeAsync(() => { const currentUser = metisUser1; metisServiceGetUserStub.mockReturnValue(currentUser); component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ filterToUnresolved: false, filterToOwn: true, filterToAnsweredOrReacted: false, }); const filterOwnCheckbox = getElement(fixture.debugElement, 'input[name=filterToOwn]'); filterOwnCheckbox.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(component.currentPostContextFilter.filterToUnresolved).toBeFalse(); expect(component.currentPostContextFilter.filterToOwn).toBeTrue(); expect(component.currentPostContextFilter.filterToAnsweredOrReacted).toBeFalse(); // actual post filtering done at server side, tested by PostIntegrationTest })); it('should fetch new posts when context filter changes to course-wide-context', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ context: { courseId: undefined, courseWideContext: CourseWideContext.ORGANIZATION, exerciseId: undefined, lectureId: undefined, }, }); const contextOptions = getElement(fixture.debugElement, 'select[name=context]'); contextOptions.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(component.posts).toEqual(metisCoursePostsWithCourseWideContext.filter((post) => post.courseWideContext === CourseWideContext.ORGANIZATION)); })); it('should fetch new posts when context filter changes to exercise', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ context: { courseId: undefined, courseWideContext: undefined, exerciseId: metisExercise.id, lectureId: undefined, }, }); const contextOptions = getElement(fixture.debugElement, 'select[name=context]'); contextOptions.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(component.posts).toEqual(metisExercisePosts); })); it('should fetch new posts when context filter changes to lecture', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); component.formGroup.patchValue({ context: { courseId: undefined, courseWideContext: undefined, exerciseId: undefined, lectureId: metisLecture.id, }, }); const contextOptions = getElement(fixture.debugElement, 'select[name=context]'); contextOptions.dispatchEvent(new Event('change')); tick(); fixture.detectChanges(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(component.posts).toEqual(metisLecturePosts); })); it('should invoke metis service forcing a reload when sort criterion changed', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); const sortByOptions = getElement(fixture.debugElement, 'select[name=sortBy]'); sortByOptions.dispatchEvent(new Event('change')); expectGetFilteredPostsToBeCalled(); })); it('should invoke metis service forcing a reload when sort direction changed', fakeAsync(() => { component.ngOnInit(); tick(); fixture.detectChanges(); const selectedDirectionOption = getElement(fixture.debugElement, '.clickable'); selectedDirectionOption.dispatchEvent(new Event('click')); expectGetFilteredPostsToBeCalled(); })); it('should fetch next page of posts if exists', fakeAsync(() => { component.itemsPerPage = 5; component.ngOnInit(); tick(); fixture.detectChanges(); component.fetchNextPage(); // next page does not exist, service method won't be called again component.fetchNextPage(); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); expect(metisServiceGetFilteredPostsSpy).toHaveBeenNthCalledWith( 3, { ...component.currentPostContextFilter, page: 1, pageSize: component.itemsPerPage, pagingEnabled: true, }, false, ); })); function expectGetFilteredPostsToBeCalled() { expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledWith({ courseId: metisCourse.id, courseWideContext: undefined, exerciseId: undefined, lectureId: undefined, page: component.page - 1, pageSize: component.itemsPerPage, pagingEnabled: true, postSortCriterion: 'CREATION_DATE', sortingOrder: 'DESCENDING', }); expect(metisServiceGetFilteredPostsSpy).toHaveBeenCalledTimes(3); } describe('sorting of posts', () => { it('should distinguish context filter options for properly show them in form', () => { let result = component.compareContextFilterOptionFn({ courseId: metisCourse.id }, { courseId: metisCourse.id }); expect(result).toBeTrue(); result = component.compareContextFilterOptionFn({ courseId: metisCourse.id }, { courseId: 99 }); expect(result).toBeFalse(); result = component.compareContextFilterOptionFn({ lectureId: metisLecture.id }, { lectureId: metisLecture.id }); expect(result).toBeTrue(); result = component.compareContextFilterOptionFn({ lectureId: metisLecture.id }, { lectureId: 99 }); expect(result).toBeFalse(); result = component.compareContextFilterOptionFn({ exerciseId: metisExercise.id }, { exerciseId: metisExercise.id }); expect(result).toBeTrue(); result = component.compareContextFilterOptionFn({ exerciseId: metisExercise.id }, { exerciseId: 99 }); expect(result).toBeFalse(); result = component.compareContextFilterOptionFn({ courseWideContext: CourseWideContext.ORGANIZATION }, { courseWideContext: CourseWideContext.ORGANIZATION }); expect(result).toBeTrue(); result = component.compareContextFilterOptionFn({ courseWideContext: CourseWideContext.ORGANIZATION }, { courseWideContext: CourseWideContext.TECH_SUPPORT }); expect(result).toBeFalse(); }); }); });
the_stack
export interface AddressDetail { adminArea?: string; country?: string; countryCode?: string; locality?: string; postalCode?: string; streetNumber?: string; subAdminArea?: string; subLocality?: string; tertiaryAdminArea?: string; thoroughfare?: string; } export interface AutocompletePrediction { description?: string; matchedKeywords?: Word[]; matchedWords?: Word[]; } export interface ChildrenNode { depAndArr?: string; domeAndInt?: string; formatAddress?: string; hwPoiTypes?: string[]; location?: Coordinate; name?: string; siteId?: string; } export interface Coordinate { lat: number; lng: number; } export interface CoordinateBounds { northeast: Coordinate; southwest: Coordinate; } export interface DetailSearchRequest { language?: string; politicalView?: string siteId: string; children?: boolean; } export interface DetailSearchResponse { site: Site; } export interface NearbySearchRequest { hwPoiType?: HwLocationType; language?: string; location: Coordinate; pageIndex?: number; pageSize?: number; poiType?: LocationType; politicalView?: string; query?: string; radius?: number; strictBounds?: boolean; } export interface NearbySearchResponse { sites: Site[]; totalCount: number; } export interface OpeningHours { periods?: Period[]; texts?: string[]; } export interface Period { close?: TimeOfWeek; open?: TimeOfWeek; } export interface Poi { businessStatus?: string; childrenNodes?: ChildrenNode[]; internationalPhone?: string; openingHours?: OpeningHours; phone?: string; photoUrls?: string[]; poiTypes?: LocationType[]; priceLevel: number; hwPoiTypes?: string[]; rating?: number; websiteUrl?: string; } export interface QueryAutocompleteRequest { language?: string; location?: Coordinate; politicalView?: string; query: string; radius?: number; children?: boolean; } export interface QueryAutocompleteResponse { sites: Site[]; predictions: AutocompletePrediction[]; } export interface QuerySuggestionRequest { bounds?: CoordinateBounds; countryCode?: string; language?: string; location?: Coordinate; poiTypes?: LocationType[]; politicalView?: string; query: string; radius?: number; children?: boolean; strictBounds?: boolean; } export interface QuerySuggestionResponse { sites: Site[]; } export interface SearchStatus { errorCode: string; errorMessage: string; } export interface Site { address?: AddressDetail; distance?: number; formatAddress?: string; location?: Coordinate; name?: string; poi?: Poi; prediction?: AutocompletePrediction; siteId?: string; utcOffset?: number; viewport?: CoordinateBounds; } export interface TextSearchRequest { countryCode?: string; hwPoiType?: HwLocationType; language?: string; location?: Coordinate; pageIndex?: number; pageSize?: number; poiType?: LocationType; politicalView?: string; query: string; radius?: number; children: boolean; } export interface TextSearchResponse { sites: Site[]; totalCount: number; } export interface TimeOfWeek { day?: number; time?: string; } export interface Word { offset: number; value: string; } export interface SearchFilter { bounds?: CoordinateBounds; countryCode?: string; language?: string; location?: Coordinate; poiType?: LocationType[]; politicalView?: string; query?: string; radius?: number; strictBounds?: boolean; children?: boolean; } // ENUM export enum LocationType { ACCOUNTING = "ACCOUNTING", ADDRESS = "ADDRESS", ADMINISTRATIVE_AREA_LEVEL_1 = "ADMINISTRATIVE_AREA_LEVEL_1", ADMINISTRATIVE_AREA_LEVEL_2 = "ADMINISTRATIVE_AREA_LEVEL_2", ADMINISTRATIVE_AREA_LEVEL_3 = "ADMINISTRATIVE_AREA_LEVEL_3", ADMINISTRATIVE_AREA_LEVEL_4 = "ADMINISTRATIVE_AREA_LEVEL_4", ADMINISTRATIVE_AREA_LEVEL_5 = "ADMINISTRATIVE_AREA_LEVEL_5", AIRPORT = "AIRPORT", AMUSEMENT_PARK = "AMUSEMENT_PARK", AQUARIUM = "AQUARIUM", ARCHIPELAGO = "ARCHIPELAGO", ART_GALLERY = "ART_GALLERY", ATM = "ATM", BAKERY = "BAKERY", BANK = "BANK", BAR = "BAR", BEAUTY_SALON = "BEAUTY_SALON", BICYCLE_STORE = "BICYCLE_STORE", BOOK_STORE = "BOOK_STORE", BOWLING_ALLEY = "BOWLING_ALLEY", BUS_STATION = "BUS_STATION", CAFE = "CAFE", CAMPGROUND = "CAMPGROUND", CAPITAL = "CAPITAL", CAPITAL_CITY = "CAPITAL_CITY", CAR_DEALER = "CAR_DEALER", CAR_RENTAL = "CAR_RENTAL", CAR_REPAIR = "CAR_REPAIR", CAR_WASH = "CAR_WASH", CASINO = "CASINO", CEMETERY = "CEMETERY", CHURCH = "CHURCH", CITIES = "CITIES", CITY_HALL = "CITY_HALL", CLOTHING_STORE = "CLOTHING_STORE", COLLOQUIAL_AREA = "COLLOQUIAL_AREA", CONTINENT = "CONTINENT", CONVENIENCE_STORE = "CONVENIENCE_STORE", COUNTRY = "COUNTRY", COURTHOUSE = "COURTHOUSE", DENTIST = "DENTIST", DEPARTMENT_STORE = "DEPARTMENT_STORE", DOCTOR = "DOCTOR", DRUGSTORE = "DRUGSTORE", ELECTRICIAN = "ELECTRICIAN", ELECTRONICS_STORE = "ELECTRONICS_STORE", EMBASSY = "EMBASSY", ESTABLISHMENT = "ESTABLISHMENT", FINANCE = "FINANCE", FIRE_STATION = "FIRE_STATION", FLOOR = "FLOOR", FLORIST = "FLORIST", FOOD = "FOOD", FUNERAL_HOME = "FUNERAL_HOME", FURNITURE_STORE = "FURNITURE_STORE", GAS_STATION = "GAS_STATION", GENERAL_CITY = "GENERAL_CITY", GENERAL_CONTRACTOR = "GENERAL_CONTRACTOR", GEOCODE = "GEOCODE", GROCERY_OR_SUPERMARKET = "GROCERY_OR_SUPERMARKET", GYM = "GYM", HAIR_CARE = "HAIR_CARE", HAMLET = "HAMLET", HARDWARE_STORE = "HARDWARE_STORE", HEALTH = "HEALTH", HINDU_TEMPLE = "HINDU_TEMPLE", HOME_GOODS_STORE = "HOME_GOODS_STORE", HOSPITAL = "HOSPITAL", INSURANCE_AGENCY = "INSURANCE_AGENCY", INTERSECTION = "INTERSECTION", JEWELRY_STORE = "JEWELRY_STORE", LAUNDRY = "LAUNDRY", LAWYER = "LAWYER", LIBRARY = "LIBRARY", LIGHT_RAIL_STATION = "LIGHT_RAIL_STATION", LIQUOR_STORE = "LIQUOR_STORE", LOCALITY = "LOCALITY", LOCAL_GOVERNMENT_OFFICE = "LOCAL_GOVERNMENT_OFFICE", LOCKSMITH = "LOCKSMITH", LODGING = "LODGING", MEAL_DELIVERY = "MEAL_DELIVERY", MEAL_TAKEAWAY = "MEAL_TAKEAWAY", MOSQUE = "MOSQUE", MOVIE_RENTAL = "MOVIE_RENTAL", MOVIE_THEATER = "MOVIE_THEATER", MOVING_COMPANY = "MOVING_COMPANY", MUSEUM = "MUSEUM", NATURAL_FEATURE = "NATURAL_FEATURE", NEIGHBORHOOD = "NEIGHBORHOOD", NIGHT_CLUB = "NIGHT_CLUB", OTHER = "OTHER", PAINTER = "PAINTER", PARK = "PARK", PARKING = "PARKING", PET_STORE = "PET_STORE", PHARMACY = "PHARMACY", PHYSIOTHERAPIST = "PHYSIOTHERAPIST", PLACE_OF_WORSHIP = "PLACE_OF_WORSHIP", PLUMBER = "PLUMBER", POINT_OF_INTEREST = "POINT_OF_INTEREST", POLICE = "POLICE", POLITICAL = "POLITICAL", POSTAL_CODE = "POSTAL_CODE", POSTAL_CODE_PREFIX = "POSTAL_CODE_PREFIX", POSTAL_CODE_SUFFIX = "POSTAL_CODE_SUFFIX", POSTAL_TOWN = "POSTAL_TOWN", POST_BOX = "POST_BOX", POST_OFFICE = "POST_OFFICE", PREMISE = "PREMISE", PRIMARY_SCHOOL = "PRIMARY_SCHOOL", REAL_ESTATE_AGENCY = "REAL_ESTATE_AGENCY", REGION = "REGION", REGIONS = "REGIONS", RESTAURANT = "RESTAURANT", ROOFING_CONTRACTOR = "ROOFING_CONTRACTOR", ROOM = "ROOM", ROUTE = "ROUTE", RV_PARK = "RV_PARK", SCHOOL = "SCHOOL", SECONDARY_SCHOOL = "SECONDARY_SCHOOL", SHOE_STORE = "SHOE_STORE", SHOPPING_MALL = "SHOPPING_MALL", SPA = "SPA", STADIUM = "STADIUM", STORAGE = "STORAGE", STORE = "STORE", STREET_ADDRESS = "STREET_ADDRESS", STREET_NUMBER = "STREET_NUMBER", SUBLOCALITY = "SUBLOCALITY", SUBLOCALITY_LEVEL_1 = "SUBLOCALITY_LEVEL_1", SUBLOCALITY_LEVEL_2 = "SUBLOCALITY_LEVEL_2", SUBLOCALITY_LEVEL_3 = "SUBLOCALITY_LEVEL_3", SUBLOCALITY_LEVEL_4 = "SUBLOCALITY_LEVEL_4", SUBLOCALITY_LEVEL_5 = "SUBLOCALITY_LEVEL_5", SUBPREMISE = "SUBPREMISE", SUBWAY_STATION = "SUBWAY_STATION", SUPERMARKET = "SUPERMARKET", SYNAGOGUE = "SYNAGOGUE", TAXI_STAND = "TAXI_STAND", TOURIST_ATTRACTION = "TOURIST_ATTRACTION", TOWN = "TOWN", TOWN_SQUARE = "TOWN_SQUARE", TRAIN_STATION = "TRAIN_STATION", TRANSIT_STATION = "TRANSIT_STATION", TRAVEL_AGENCY = "TRAVEL_AGENCY", UNIVERSITY = "UNIVERSITY", VETERINARY_CARE = "VETERINARY_CARE", ZOO = "ZOO" } export enum HwLocationType { ACCESS_GATEWAY = "ACCESS_GATEWAY", ADDRESS = "ADDRESS", ADMINISTRATIVE_AREA_LEVEL_1 = "ADMINISTRATIVE_AREA_LEVEL_1", ADMINISTRATIVE_AREA_LEVEL_2 = "ADMINISTRATIVE_AREA_LEVEL_2", ADMINISTRATIVE_AREA_LEVEL_3 = "ADMINISTRATIVE_AREA_LEVEL_3", ADMINISTRATIVE_AREA_LEVEL_4 = "ADMINISTRATIVE_AREA_LEVEL_4", ADMIN_FEATURE = "ADMIN_FEATURE", ADVENTURE_SPORTS_VENUE = "ADVENTURE_SPORTS_VENUE", ADVENTURE_VEHICLE_TRAIL = "ADVENTURE_VEHICLE_TRAIL", ADVERTISING_AND_MARKETING_COMPANY = "ADVERTISING_AND_MARKETING_COMPANY", AFGHAN_RESTAURANT = "AFGHAN_RESTAURANT", AFRICAN_RESTAURANT = "AFRICAN_RESTAURANT", AGRICULTURAL_SUPPLY_STORE = "AGRICULTURAL_SUPPLY_STORE", AGRICULTURAL_TECHNOLOGY_COMPANY = "AGRICULTURAL_TECHNOLOGY_COMPANY", AGRICULTURE_BUSINESS = "AGRICULTURE_BUSINESS", AIRFIELD = "AIRFIELD", AIRLINE = "AIRLINE", AIRLINE_ACCESS = "AIRLINE_ACCESS", AIRPORT = "AIRPORT", ALGERIAN_RESTAURANT = "ALGERIAN_RESTAURANT", AMBULANCE_UNIT = "AMBULANCE_UNIT", AMERICAN_RESTAURANT = "AMERICAN_RESTAURANT", AMPHITHEATER = "AMPHITHEATER", AMUSEMENT_ARCADE = "AMUSEMENT_ARCADE", AMUSEMENT_PARK = "AMUSEMENT_PARK", AMUSEMENT_PLACE = "AMUSEMENT_PLACE", ANIMAL_SERVICE_STORE = "ANIMAL_SERVICE_STORE", ANIMAL_SHELTER = "ANIMAL_SHELTER", ANTIQUE_ART_STORE = "ANTIQUE_ART_STORE", APARTMENT = "APARTMENT", AQUATIC_ZOO_MARINE_PARK = "AQUATIC_ZOO_MARINE_PARK", ARABIAN_RESTAURANT = "ARABIAN_RESTAURANT", ARBORETA_BOTANICAL_GARDENS = "ARBORETA_BOTANICAL_GARDENS", ARCH = "ARCH", ARGENTINEAN_RESTAURANT = "ARGENTINEAN_RESTAURANT", ARMENIAN_RESTAURANT = "ARMENIAN_RESTAURANT", ART_MUSEUM = "ART_MUSEUM", ART_SCHOOL = "ART_SCHOOL", ASHRAM = "ASHRAM", ASIAN_RESTAURANT = "ASIAN_RESTAURANT", ATHLETIC_STADIUM = "ATHLETIC_STADIUM", ATV_SNOWMOBILE_DEALER = "ATV_SNOWMOBILE_DEALER", AUSTRALIAN_RESTAURANT = "AUSTRALIAN_RESTAURANT", AUSTRIAN_RESTAURANT = "AUSTRIAN_RESTAURANT", AUTOMATIC_TELLER_MACHINE = "AUTOMATIC_TELLER_MACHINE", AUTOMOBILE_ACCESSORIES_SHOP = "AUTOMOBILE_ACCESSORIES_SHOP", AUTOMOBILE_COMPANY = "AUTOMOBILE_COMPANY", AUTOMOBILE_MANUFACTURING_COMPANY = "AUTOMOBILE_MANUFACTURING_COMPANY", AUTOMOTIVE = "AUTOMOTIVE", AUTOMOTIVE_DEALER = "AUTOMOTIVE_DEALER", AUTOMOTIVE_GLASS_REPLACEMENT_SHOP = "AUTOMOTIVE_GLASS_REPLACEMENT_SHOP", AUTOMOTIVE_REPAIR_SHOP = "AUTOMOTIVE REPAIR_SHOP", BADMINTON_COURT = "BADMINTON_COURT", BAGS_LEATHERWEAR_SHOP = "BAGS_LEATHERWEAR_SHOP", BAKERY = "BAKERY", BANK = "BANK", BANQUET_ROOM = "BANQUET_ROOM", BAR = "BAR", BARBECUE_RESTAURANT = "BARBECUE_RESTAURANT", BASEBALL_FIELD = "BASEBALL_FIELD", BASKETBALL_COURT = "BASKETBALL_COURT", BASQUE_RESTAURANT = "BASQUE_RESTAURANT", BATTLEFIELD = "BATTLEFIELD", BAY = "BAY", BEACH = "BEACH", BEACH_CLUB = "BEACH_CLUB", BEAUTY_SALON = "BEAUTY_SALON", BEAUTY_SUPPLY_SHOP = "BEAUTY_SUPPLY_SHOP", BED_BREAKFAST_GUEST_HOUSES = "BED_BREAKFAST_GUEST_HOUSES", BELGIAN_RESTAURANT = "BELGIAN_RESTAURANT", BETTING_STATION = "BETTING_STATION", BICYCLE_PARKING_PLACE = "BICYCLE_PARKING_PLACE", BICYCLE_SHARING_LOCATION = "BICYCLE_SHARING_LOCATION", BILLIARDS_POOL_HALL = "BILLIARDS_POOL_HALL", BISTRO = "BISTRO", BLOOD_BANK = "BLOOD_BANK", BOATING_EQUIPMENT_ACCESSORIES_STORE = "BOATING_EQUIPMENT_ACCESSORIES_STORE", BOAT_DEALER = "BOAT_DEALER", BOAT_FERRY = "BOAT_FERRY", BOAT_LAUNCHING_RAMP = "BOAT_LAUNCHING_RAMP", BODYSHOPS = "BODYSHOPS", BOLIVIAN_RESTAURANT = "BOLIVIAN_RESTAURANT", BOOKSTORE = "BOOKSTORE", BORDER_POST = "BORDER_POST", BOSNIAN_RESTAURANT = "BOSNIAN_RESTAURANT", BOWLING_FIELD = "BOWLING_FIELD", BRAZILIAN_RESTAURANT = "BRAZILIAN_RESTAURANT", BRIDGE = "BRIDGE", BRIDGE_TUNNEL_ENGINEERING_COMPANY = "BRIDGE_TUNNEL_ENGINEERING_COMPANY", BRITISH_RESTAURANT = "BRITISH_RESTAURANT", BUDDHIST_TEMPLE = "BUDDHIST_TEMPLE", BUFFET = "BUFFET", BUILDING = "BUILDING", BULGARIAN_RESTAURANT = "BULGARIAN_RESTAURANT", BUNGALOW = "BUNGALOW", BURMESE_RESTAURANT = "BURMESE_RESTAURANT", BUSINESS = "BUSINESS", BUSINESS_PARK = "BUSINESS_PARK", BUSINESS_SERVICES_COMPANY = "BUSINESS_SERVICES_COMPANY", BUS_CHARTER_RENTAL_COMPANY = "BUS_CHARTER_RENTAL_COMPANY", BUS_COMPANY = "BUS_COMPANY", BUS_DEALER = "BUS_DEALER", BUS_STOP = "BUS_STOP", CABARET = "CABARET", CABINS_LODGES = "CABINS_LODGES", CABLE_TELEPHONE_COMPANY = "CABLE_TELEPHONE_COMPANY", CAFE = "CAFE", CAFETERIA = "CAFETERIA", CAFE_PUB = "CAFE_PUB", CALIFORNIAN_RESTAURANT = "CALIFORNIAN_RESTAURANT", CAMBODIAN_RESTAURANT = "CAMBODIAN_RESTAURANT", CAMPING_GROUND = "CAMPING_GROUND", CANADIAN_RESTAURANT = "CANADIAN_RESTAURANT", CAPE = "CAPE", CAPITAL = "CAPITAL", CAPITAL_CITY = "CAPITAL_CITY", CARAVAN_SITE = "CARAVAN_SITE", CARGO_CENTER = "CARGO_CENTER", CARIBBEAN_RESTAURANT = "CARIBBEAN_RESTAURANT", CARPET_FLOOR_COVERING_STORE = "CARPET_FLOOR_COVERING_STORE", CAR_CLUB = "CAR_CLUB", CAR_DEALER = "CAR_DEALER", CAR_RENTAL = "CAR_RENTAL", CAR_RENTAL_COMPANY = "CAR_RENTAL_COMPANY", CAR_WASH = "CAR_WASH", CAR_WASH_SUB = "CAR_WASH_SUB", CASINO = "CASINO", CATERING_COMPANY = "CATERING_COMPANY", CAVE = "CAVE", CD_DVD_VIDEO_RENTAL_STORE = "CD_DVD_VIDEO_RENTAL_STORE", CD_DVD_VIDEO_STORE = "CD_DVD_VIDEO_STORE", CD_DVD_VIDEO_STORE_SUB = "CD_DVD_VIDEO_STORE_SUB", CEMETERY = "CEMETERY", CHALET = "CHALET", CHEMICAL_COMPANY = "CHEMICAL_COMPANY", CHICKEN_RESTAURANT = "CHICKEN_RESTAURANT", CHILDRENS_MUSEUM = "CHILDRENS_MUSEUM", CHILD_CARE_FACILITY = "CHILD_CARE_FACILITY", CHILEAN_RESTAURANT = "CHILEAN_RESTAURANT", CHINESE_MEDICINE_HOSPITAL = "CHINESE_MEDICINE_HOSPITAL", CHINESE_RESTAURANT = "CHINESE_RESTAURANT", CHRISTMAS_HOLIDAY_STORE = "CHRISTMAS_HOLIDAY_STORE", CHURCH = "CHURCH", CINEMA = "CINEMA", CINEMA_SUB = "CINEMA_SUB", CITIES = "CITIES", CITY_CENTER = "CITY_CENTER", CITY_HALL = "CITY_HALL", CIVIC_COMMUNITY_CENTER = "CIVIC_COMMUNITY_CENTER", CLEANING_SERVICE_COMPANY = "CLEANING_SERVICE_COMPANY", CLOTHING_ACCESSORIES_STORE = "CLOTHING_ACCESSORIES_STORE", CLUB_ASSOCIATION = "CLUB_ASSOCIATION", COACH_PARKING_AREA = "COACH_PARKING_AREA", COACH_STATION = "COACH_STATION", COCKTAIL_BAR = "COCKTAIL_BAR", COFFEE_SHOP = "COFFEE_SHOP", COLLEGE_UNIVERSITY = "COLLEGE_UNIVERSITY", COLOMBIAN_RESTAURANT = "COLOMBIAN_RESTAURANT", COMEDY_CLUB = "COMEDY_CLUB", COMMERCIAL_BUILDING = "COMMERCIAL_BUILDING", COMMUNITY_CENTER = "COMMUNITY_CENTER", COMPANY = "COMPANY", COMPUTER_AND_DATA_SERVICES_CORPORATION = "COMPUTER_AND_DATA_SERVICES_CORPORATION", COMPUTER_SOFTWARE_COMPANY = "COMPUTER_SOFTWARE_COMPANY", COMPUTER_STORE = "COMPUTER_STORE", CONCERT_HALL = "CONCERT_HALL", CONDOMINIUM_COMPLEX = "CONDOMINIUM_COMPLEX", CONSTRUCTION_COMPANY = "CONSTRUCTION_COMPANY", CONSTRUCTION_MATERIAL_EQUIPMENT_SHOP = "CONSTRUCTION_MATERIAL_EQUIPMENT_SHOP", CONSUMER_ELECTRONICS_STORE = "CONSUMER_ELECTRONICS_STORE", CONTINENT = "CONTINENT", CONVENIENCE_STORE = "CONVENIENCE_STORE", CORSICAN_RESTAURANT = "CORSICAN_RESTAURANT", COTTAGE = "COTTAGE", COUNTRY = "COUNTRY", COUNTY = "COUNTY", COUNTY_COUNCIL = "COUNTY_COUNCIL", COURIER_DROP_BOX = "COURIER_DROP_BOX", COURTHOUSE = "COURTHOUSE", COVE = "COVE", CREOLE_CAJUN_RESTAURANT = "CREOLE_CAJUN_RESTAURANT", CREPERIE = "CREPERIE", CRICKET_GROUND = "CRICKET_GROUND", CUBAN_RESTAURANT = "CUBAN_RESTAURANT", CULINARY_SCHOOL = "CULINARY_SCHOOL", CULTURAL_CENTER = "CULTURAL_CENTER", CURRENCY_EXCHANGE = "CURRENCY_EXCHANGE", CURTAIN_TEXTILE_STORE = "CURTAIN_TEXTILE_STORE", CYPRIOT_RESTAURANT = "CYPRIOT_RESTAURANT", CZECH_RESTAURANT = "CZECH_RESTAURANT", DAM = "DAM", DANCE_STUDIO_SCHOOL = "DANCE_STUDIO_SCHOOL", DANCING_CLUB = "DANCING_CLUB", DANISH_RESTAURANT = "DANISH_RESTAURANT", DELICATESSEN_STORE = "DELICATESSEN_STORE", DELIVERY_ENTRANCE = "DELIVERY_ENTRANCE", DENTAL_CLINIC = "DENTAL_CLINIC", DEPARTMENT_STORE = "DEPARTMENT_STORE", DHARMA_TEMPLE = "DHARMA_TEMPLE", DINNER_THEATER = "DINNER_THEATER", DISCOTHEQUE = "DISCOTHEQUE", DIVERSIFIED_FINANCIAL_SERVICE_COMPANY = "DIVERSIFIED_FINANCIAL_SERVICE_COMPANY", DIVING_CENTER = "DIVING_CENTER", DOCK = "DOCK", DOMINICAN_RESTAURANT = "DOMINICAN_RESTAURANT", DONGBEI_RESTAURANT = "DONGBEI_RESTAURANT", DOUGHNUT_SHOP = "DOUGHNUT_SHOP", DO_IT_YOURSELF_CENTERS = "DO_IT_YOURSELF_CENTERS", DRIVE_IN_CINEMA = "DRIVE_IN_CINEMA", DRIVE_THROUGH_BOTTLE_SHOP = "DRIVE_THROUGH_BOTTLE_SHOP", DRIVING_SCHOOL = "DRIVING_SCHOOL", DRUGSTORE = "DRUGSTORE", DRY_CLEANERS = "DRY_CLEANERS", DUNE = "DUNE", DUTCH_RESTAURANT = "DUTCH_RESTAURANT", EARTHQUAKE_ASSEMBLY_POINT_ = "EARTHQUAKE_ASSEMBLY_POINT_", EATING_DRINKING = "EATING_DRINKING", EDUCATION_INSTITUTION = "EDUCATION_INSTITUTION", EGYPTIAN_RESTAURANT = "EGYPTIAN_RESTAURANT", ELECTRICAL_APPLIANCE_STORE = "ELECTRICAL_APPLIANCE_STORE", ELECTRICAL_APPLIANCE_STORE_SUB = "ELECTRICAL_APPLIANCE_STORE_SUB", ELECTRIC_VEHICLE_CHARGING_STATION = "ELECTRIC_VEHICLE_CHARGING_STATION", ELECTRONICS_COMPANY = "ELECTRONICS_COMPANY", ELECTRONICS_STORE = "ELECTRONICS_STORE", EMBASSY = "EMBASSY", EMERGENCY_ASSEMBLY_POINT = "EMERGENCY_ASSEMBLY_POINT", EMERGENCY_MEDICAL_SERVICE_CENTER = "EMERGENCY_MEDICAL_SERVICE_CENTER", EMERGENCY_ROOM = "EMERGENCY_ROOM", ENGLISH_RESTAURANT = "ENGLISH_RESTAURANT", ENTERTAINMENT_CABARET_LIVE = "ENTERTAINMENT_CABARET_LIVE", ENTERTAINMENT_PLACE = "ENTERTAINMENT_PLACE", EQUIPMENT_RENTAL_COMPANY = "EQUIPMENT_RENTAL_COMPANY", EROTIC_RESTAURANT = "EROTIC_RESTAURANT", ESTABLISHMENT = "ESTABLISHMENT", ETHIOPIAN_RESTAURANT = "ETHIOPIAN_RESTAURANT", EXCHANGE = "EXCHANGE", EXHIBITION_CONVENTION_CENTER = "EXHIBITION_CONVENTION_CENTER", EXOTIC_RESTAURANT = "EXOTIC_RESTAURANT", FACTORY_OUTLETS = "FACTORY_OUTLETS", FAIRGROUND = "FAIRGROUND", FARM = "FARM", FARMER_MARKET = "FARMER_MARKET", FAST_FOOD_RESTAURANT = "FAST_FOOD_RESTAURANT", FERRY_TERMINAL = "FERRY_TERMINAL", FILIPINO_RESTAURANT = "FILIPINO_RESTAURANT", FINNISH_RESTAURANT = "FINNISH_RESTAURANT", FIRE_ASSEMBLY_POINT = "FIRE_ASSEMBLY_POINT", FIRE_STATION_BRIGADE = "FIRE_STATION_BRIGADE", FISHING_HUNTING_AREA = "FISHING_HUNTING_AREA", FISH_STORE = "FISH_STORE", FITNESS_CLUB_CENTER = "FITNESS_CLUB_CENTER", FIVE_STAR_HOTEL = "FIVE_STAR_HOTEL", FLATS_APARTMENT_COMPLEX = "FLATS_APARTMENT_COMPLEX", FLOOD_ASSEMBLY_POINT = "FLOOD_ASSEMBLY_POINT", FLORISTS = "FLORISTS", FLYING_CLUB = "FLYING_CLUB", FONDUE_RESTAURANT = "FONDUE_RESTAURANT", FOOD_DRINK_SHOP = "FOOD_DRINK_SHOP", FOOD_MARKET = "FOOD_MARKET", FOOTBALL_FIELD = "FOOTBALL_FIELD", FOREST_AREA = "FOREST_AREA", FOUR_STAR_HOTEL = "FOUR_STAR_HOTEL", FRENCH_RESTAURANT = "FRENCH_RESTAURANT", FUNERAL_SERVICE_COMPANY = "FUNERAL_SERVICE_COMPANY", FURNITURE_ACCESSORIES_STORE = "FURNITURE_ACCESSORIES_STORE", FURNITURE_STORE = "FURNITURE_STORE", FUSION_RESTAURANT = "FUSION_RESTAURANT", GALLERY = "GALLERY", GARDENING_CERVICE_CENTER = "GARDENING_CERVICE_CENTER", GENERAL_AUTO_REPAIR_SERVICE_CENTER = "GENERAL_AUTO_REPAIR_SERVICE_CENTER", GENERAL_CITY = "GENERAL_CITY", GENERAL_CLINIC = "GENERAL_CLINIC", GENERAL_HOSPITAL = "GENERAL_HOSPITAL", GENERAL_POST_OFFICE = "GENERAL_POST_OFFICE", GEOCODE = "GEOCODE", GEOGRAPHIC_FEATURE = "GEOGRAPHIC_FEATURE", GERMAN_RESTAURANT = "GERMAN_RESTAURANT", GIFT_STORE = "GIFT_STORE", GLASSWARE_CERAMIC_SHOP = "GLASSWARE_CERAMIC_SHOP", GLASS_WINDOW_STORE = "GLASS_WINDOW_STORE", GOLD_EXCHANGE = "GOLD_EXCHANGE", GOLF_COURSE = "GOLF_COURSE", GOVERNMENT_OFFICE = "GOVERNMENT_OFFICE", GOVERNMENT_PUBLIC_SERVICE = "GOVERNMENT_PUBLIC_SERVICE", GREEK_RESTAURANT = "GREEK_RESTAURANT", GREENGROCERY = "GREENGROCERY", GRILL = "GRILL", GROCERY = "GROCERY", GUANGDONG_RESTAURANT = "GUANGDONG_RESTAURANT", GURUDWARA = "GURUDWARA", HAIR_SALON_BARBERSHOP = "HAIR_SALON_BARBERSHOP", HAMBURGER_RESTAURANT = "HAMBURGER_RESTAURANT", HAMLET = "HAMLET", HARBOR = "HARBOR", HARDWARE_STORE = "HARDWARE_STORE", HEALTHCARE_SERVICE_CENTER = "HEALTHCARE_SERVICE_CENTER", HEALTH_CARE = "HEALTH_CARE", HELIPAD_HELICOPTER_LANDING = "HELIPAD_HELICOPTER_LANDING", HIGHWAY_EXIT = "HIGHWAY_EXIT", HIGHWAY__ENTRANCE = "HIGHWAY__ENTRANCE", HIGH_SCHOOL = "HIGH_SCHOOL", HIKING_TRAIL = "HIKING_TRAIL", HILL = "HILL", HINDU_TEMPLE = "HINDU_TEMPLE", HISTORICAL_PARK = "HISTORICAL_PARK", HISTORIC_SITE = "HISTORIC_SITE", HISTORY_MUSEUM = "HISTORY_MUSEUM", HOBBY_SHOP = "HOBBY_SHOP", HOCKEY_CLUB = "HOCKEY_CLUB", HOCKEY_FIELD = "HOCKEY_FIELD", HOLIDAY_HOUSE_RENTAL = "HOLIDAY_HOUSE_RENTAL", HOME_APPLIANCE_REPAIR_COMPANY = "HOME_APPLIANCE_REPAIR_COMPANY", HOME_GOODS_STORE = "HOME_GOODS_STORE", HORSE_RACING_TRACK = "HORSE_RACING_TRACK", HORSE_RIDING_FIELD = "HORSE_RIDING_FIELD", HORSE_RIDING_TRAIL = "HORSE_RIDING_TRAIL", HORTICULTURE_COMPANY = "HORTICULTURE_COMPANY", HOSPITAL_FOR_WOMEN_AND_CHILDREN = "HOSPITAL_FOR_WOMEN_AND_CHILDREN", HOSPITAL_POLYCLINIC = "HOSPITAL_POLYCLINIC", HOSTEL = "HOSTEL", HOTEL = "HOTEL", HOTELS_WITH_LESS_THAN_TWO_STARS = "HOTELS_WITH_LESS_THAN_TWO_STARS", HOTEL_MOTEL = "HOTEL_MOTEL", HOT_POT_RESTAURANT = "HOT_POT_RESTAURANT", HOUSEHOLD_APPLIANCE_STORE = "HOUSEHOLD_APPLIANCE_STORE", HUNAN_RESTAURANT = "HUNAN_RESTAURANT", HUNGARIAN_RESTAURANT = "HUNGARIAN_RESTAURANT", ICE_CREAM_PARLOR = "ICE_CREAM_PARLOR", ICE_HOCKEY_RINK = "ICE_HOCKEY_RINK", ICE_SKATING_RINK = "ICE_SKATING_RINK", IMPORTANT_TOURIST_ATTRACTION = "IMPORTANT_TOURIST_ATTRACTION", IMPORT_AND_EXPORT_DISTRIBUTION_COMPANY = "IMPORT_AND_EXPORT_DISTRIBUTION_COMPANY", INDIAN_RESTAURANT = "INDIAN_RESTAURANT", INDONESIAN_RESTAURANT = "INDONESIAN_RESTAURANT", INDUSTRIAL_BUILDING = "INDUSTRIAL_BUILDING", INFORMAL_MARKET = "INFORMAL_MARKET", INSURANCE_COMPANY = "INSURANCE_COMPANY", INTERCITY_RAILWAY_STATION = "INTERCITY_RAILWAY_STATION", INTERNATIONAL_ORGANIZATION = "INTERNATIONAL_ORGANIZATION", INTERNATIONAL_RAILWAY_STATION = "INTERNATIONAL_RAILWAY_STATION", INTERNATIONAL_RESTAURANT = "INTERNATIONAL_RESTAURANT", INTERNET_CAFE = "INTERNET_CAFE", INVESTMENT_CONSULTING_FIRM = "INVESTMENT_CONSULTING_FIRM", IRANIAN_RESTAURANT = "IRANIAN_RESTAURANT", IRISH_RESTAURANT = "IRISH_RESTAURANT", ISLAND = "ISLAND", ISRAELI_RESTAURANT = "ISRAELI_RESTAURANT", ITALIAN_RESTAURANT = "ITALIAN_RESTAURANT", JAIN_TEMPLE = "JAIN_TEMPLE", JAMAICAN_RESTAURANT = "JAMAICAN_RESTAURANT", JAPANESE_RESTAURANT = "JAPANESE_RESTAURANT", JAZZ_CLUB = "JAZZ_CLUB", JEWELRY_CLOCK_AND_WATCH_SHOP = "JEWELRY_CLOCK_AND_WATCH_SHOP", JEWISH_RESTAURANT = "JEWISH_RESTAURANT", JUNIOR_COLLEGE_COMMUNITY_COLLEGE = "JUNIOR_COLLEGE_COMMUNITY_COLLEGE", KARAOKE_CLUB = "KARAOKE_CLUB", KITCHEN_AND_SANITATION_STORE = "KITCHEN_AND_SANITATION_STORE", KOREAN_RESTAURANT = "KOREAN_RESTAURANT", KOSHER_RESTAURANT = "KOSHER_RESTAURANT", LAGOON = "LAGOON", LAKESHORE = "LAKESHORE", LANGUAGE_SCHOOL = "LANGUAGE_SCHOOL", LATIN_AMERICAN_RESTAURANT = "LATIN_AMERICAN_RESTAURANT", LAUNDRY = "LAUNDRY", LEBANESE_RESTAURANT = "LEBANESE_RESTAURANT", LEGAL_SERVICE_COMPANY = "LEGAL_SERVICE_COMPANY", LEISURE = "LEISURE", LEISURE_CENTER = "LEISURE_CENTER", LIBRARY = "LIBRARY", LIGHTING_STORE = "LIGHTING_STORE", LOADING_ZONE = "LOADING_ZONE", LOCAL_POST_OFFICE = "LOCAL_POST_OFFICE", LOCAL_SPECIALTY_STORE = "LOCAL_SPECIALTY_STORE", LODGING_LIVING_ACCOMMODATION = "LODGING_LIVING_ACCOMMODATION", LOTTERY_SHOP = "LOTTERY_SHOP", LUXEMBOURGIAN_RESTAURANT = "LUXEMBOURGIAN_RESTAURANT", MACROBIOTIC_RESTAURANT = "MACROBIOTIC_RESTAURANT", MAGHRIB_RESTAURANT = "MAGHRIB_RESTAURANT", MAIL_PACKAGE_FREIGHT_DELIVERY_COMPANY = "MAIL_PACKAGE_FREIGHT_DELIVERY_COMPANY", MALTESE_RESTAURANT = "MALTESE_RESTAURANT", MANUFACTURING_COMPANY = "MANUFACTURING_COMPANY", MANUFACTURING_FACTORY = "MANUFACTURING_FACTORY", MARINA = "MARINA", MARINA_SUB = "MARINA_SUB", MARINE_ELECTRONIC_EQUIPMENT_STORE = "MARINE_ELECTRONIC_EQUIPMENT_STORE", MARKET = "MARKET", MARSH_SWAMP_VLEI = "MARSH_SWAMP_VLEI", MAURITIAN_RESTAURANT = "MAURITIAN_RESTAURANT", MAUSOLEUM_GRAVE = "MAUSOLEUM_GRAVE", MEAT_STORE = "MEAT_STORE", MECHANICAL_ENGINEERING_COMPANY = "MECHANICAL_ENGINEERING_COMPANY", MEDIA_COMPANY = "MEDIA_COMPANY", MEDICAL_CLINIC = "MEDICAL_CLINIC", MEDICAL_SUPPLIES_EQUIPMENT_STORE = "MEDICAL_SUPPLIES_EQUIPMENT_STORE", MEDITERRANEAN_RESTAURANT = "MEDITERRANEAN_RESTAURANT", MEMORIAL = "MEMORIAL", MEMORIAL_PLACE = "MEMORIAL_PLACE", METRO = "METRO", MEXICAN_RESTAURANT = "MEXICAN_RESTAURANT", MICROBREWERY_BEER_GARDEN = "MICROBREWERY_BEER_GARDEN", MIDDLE_EASTERN_RESTAURANT = "MIDDLE_EASTERN_RESTAURANT", MIDDLE_SCHOOL = "MIDDLE_SCHOOL", MILITARY_AUTHORITY = "MILITARY_AUTHORITY", MILITARY_BASE = "MILITARY_BASE", MINERAL_COMPANY = "MINERAL_COMPANY", MINERAL_HOT_SPRINGS = "MINERAL_HOT_SPRINGS", MISCELLANEOUS = "MISCELLANEOUS", MOBILE_PHONE_STORE = "MOBILE_PHONE_STORE", MONGOLIAN_RESTAURANT = "MONGOLIAN_RESTAURANT", MONUMENT = "MONUMENT", MORMON_CHURCH = "MORMON_CHURCH", MOROCCAN_RESTAURANT = "MOROCCAN_RESTAURANT", MOSQUE = "MOSQUE", MOTEL = "MOTEL", MOTORCYCLE_DEALER = "MOTORCYCLE_DEALER", MOTORCYCLE_REPAIR_SHOP = "MOTORCYCLE_REPAIR_SHOP", MOTORING_ORGANIZATION_OFFICE = "MOTORING_ORGANIZATION_OFFICE", MOTORSPORT_VENUE = "MOTORSPORT_VENUE", MOUNTAIN_BIKE_TRAIL = "MOUNTAIN_BIKE_TRAIL", MOUNTAIN_PASS = "MOUNTAIN_PASS", MOUNTAIN_PEAK = "MOUNTAIN_PEAK", MOVING_STORAGE_COMPANY = "MOVING_STORAGE_COMPANY", MULTIPURPOSE_STADIUM = "MULTIPURPOSE_STADIUM", MUSEUM = "MUSEUM", MUSICAL_INSTRUMENT_STORE = "MUSICAL_INSTRUMENT_STORE", MUSIC_CENTER = "MUSIC_CENTER", MUSSEL_RESTAURANT = "MUSSEL_RESTAURANT", NAIL_SALON = "NAIL_SALON", NAMED_INTERSECTION = "NAMED_INTERSECTION", NATIONAL_ORGANIZATION = "NATIONAL_ORGANIZATION", NATIONAL_RAILWAY_STATION = "NATIONAL_RAILWAY_STATION", NATIVE_RESERVATION = "NATIVE_RESERVATION", NATURAL_ATTRACTION = "NATURAL_ATTRACTION", NATURAL_ATTRACTION_TOURIST = "NATURAL_ATTRACTION_TOURIST", NEIGHBORHOOD = "NEIGHBORHOOD", NEPALESE_RESTAURANT = "NEPALESE_RESTAURANT", NETBALL_COURT = "NETBALL_COURT", NEWSAGENTS_AND_TOBACCONISTS = "NEWSAGENTS_AND_TOBACCONISTS", NIGHTLIFE = "NIGHTLIFE", NIGHT_CLUB = "NIGHT_CLUB", NON_GOVERNMENTAL_ORGANIZATION = "NON_GOVERNMENTAL_ORGANIZATION", NORWEGIAN_RESTAURANT = "NORWEGIAN_RESTAURANT", NURSING_HOME = "NURSING_HOME", OASIS = "OASIS", OBSERVATION_DECK = "OBSERVATION_DECK", OBSERVATORY = "OBSERVATORY", OEM = "OEM", OFFICE_EQUIPMENT_STORE = "OFFICE_EQUIPMENT_STORE", OFFICE_SUPPLY_SERVICES_STORE = "OFFICE_SUPPLY_SERVICES_STORE", OIL_NATURAL_GAS_COMPANY = "OIL_NATURAL_GAS_COMPANY", OPERA = "OPERA", OPTICIANS = "OPTICIANS", ORDER_1_AREA_GOVERNMENT_OFFICE = "ORDER_1_AREA_GOVERNMENT_OFFICE", ORDER_1_AREA_POLICE_STATION = "ORDER_1_AREA_POLICE_STATION", ORDER_2_AREA_GOVERNMENT_OFFICE = "ORDER_2_AREA_GOVERNMENT_OFFICE", ORDER_3_AREA_GOVERNMENT_OFFICE = "ORDER_3_AREA_GOVERNMENT_OFFICE", ORDER_4_AREA_GOVERNMENT_OFFICE = "ORDER_4_AREA_GOVERNMENT_OFFICE", ORDER_5_AREA_GOVERNMENT_OFFICE = "ORDER_5_AREA_GOVERNMENT_OFFICE", ORDER_6_AREA_GOVERNMENT_OFFICE = "ORDER_6_AREA_GOVERNMENT_OFFICE", ORDER_7_AREA_GOVERNMENT_OFFICE = "ORDER_7_AREA_GOVERNMENT_OFFICE", ORDER_8_AREA_GOVERNMENT_OFFICE = "ORDER_8_AREA_GOVERNMENT_OFFICE", ORDER_8_AREA_POLICE_STATION = "ORDER_8_AREA_POLICE_STATION", ORDER_9_AREA_GOVERNMENT_OFFICE = "ORDER_9_AREA_GOVERNMENT_OFFICE", ORDER_9_AREA_POLICE_STATION = "ORDER_9_AREA_POLICE_STATION", ORGANIC_RESTAURANT = "ORGANIC_RESTAURANT", ORGANIZATION = "ORGANIZATION", ORIENTAL_RESTAURANT = "ORIENTAL_RESTAURANT", OUTLETS = "OUTLETS", PAGODA = "PAGODA", PAINTING_DECORATING_STORE = "PAINTING_DECORATING_STORE", PAKISTANI_RESTAURANT = "PAKISTANI_RESTAURANT", PAN = "PAN", PARK = "PARK", PARKING_GARAGE = "PARKING_GARAGE", PARKING_LOT = "PARKING_LOT", PARKING_LOT_SUB = "PARKING_LOT_SUB", PARKWAY = "PARKWAY", PARK_AND_RECREATION_AREA = "PARK_AND_RECREATION_AREA", PARK_RIDE = "PARK_RIDE", PASSENGER_TRANSPORT_TICKET_OFFICE = "PASSENGER_TRANSPORT_TICKET_OFFICE", PAWN_SHOP = "PAWN_SHOP", PEDESTRIAN_SUBWAY = "PEDESTRIAN_SUBWAY", PERSONAL_CARE_INSTITUTION = "PERSONAL_CARE_INSTITUTION", PERSONAL_SERVICE_CENTER = "PERSONAL_SERVICE_CENTER", PERUVIAN_RESTAURANT = "PERUVIAN_RESTAURANT", PETROL_STATION = "PETROL_STATION", PET_STORE = "PET_STORE", PET_SUPPLY_STORE = "PET_SUPPLY_STORE", PHARMACEUTICAL_COMPANY = "PHARMACEUTICAL_COMPANY", PHARMACY = "PHARMACY", PHOTOCOPY_SHOP = "PHOTOCOPY_SHOP", PHOTOGRAPHIC_EQUIPMENT_STORE = "PHOTOGRAPHIC_EQUIPMENT_STORE", PHOTO_SHOP = "PHOTO_SHOP", PHYSIOTHERAPY_CLINIC = "PHYSIOTHERAPY_CLINIC", PICK_UP_AND_RETURN_POINT = "PICK_UP_AND_RETURN_POINT", PICNIC_AREA = "PICNIC_AREA", PIZZA_RESTAURANT = "PIZZA_RESTAURANT", PLACE_OF_WORSHIP = "PLACE_OF_WORSHIP", PLAIN_FLAT = "PLAIN_FLAT", PLANETARIUM = "PLANETARIUM", PLATEAU = "PLATEAU", POLICE_STATION = "POLICE_STATION", POLISH_RESTAURANT = "POLISH_RESTAURANT", POLYNESIAN_RESTAURANT = "POLYNESIAN_RESTAURANT", PORTUGUESE_RESTAURANT = "PORTUGUESE_RESTAURANT", PORT_WAREHOUSE = "PORT_WAREHOUSE", POSTAL_CODE = "POSTAL_CODE", POST_OFFICE = "POST_OFFICE", PRESCHOOL = "PRESCHOOL", PRESERVED_AREA = "PRESERVED_AREA", PRIMARY_SCHOOL = "PRIMARY_SCHOOL", PRISON = "PRISON", PRIVATE_AUTHORITY = "PRIVATE_AUTHORITY", PRIVATE_CLUB = "PRIVATE_CLUB", PRODUCER_COMPANY = "PRODUCER_COMPANY", PROTECTED_AREA = "PROTECTED_AREA", PROVENÇAL_RESTAURANT = "PROVENÇAL_RESTAURANT", PUB = "PUB", PUBLIC_AMENITY = "PUBLIC_AMENITY", PUBLIC_AUTHORITY = "PUBLIC_AUTHORITY", PUBLIC_CALL_BOX = "PUBLIC_CALL_BOX", PUBLIC_HEALTH_TECHNOLOGY_COMPANY = "PUBLIC_HEALTH_TECHNOLOGY_COMPANY", PUBLIC_MARKET = "PUBLIC_MARKET", PUBLIC_RESTROOM = "PUBLIC_RESTROOM", PUBLIC_TRANSPORT_STOP = "PUBLIC_TRANSPORT_STOP", PUBLISHING_TECHNOLOGY_COMPANY = "PUBLISHING_TECHNOLOGY_COMPANY", PUB_FOOD = "PUB_FOOD", QUARRY = "QUARRY", RACE_TRACK = "RACE_TRACK", RAILWAY_SIDING = "RAILWAY_SIDING", RAILWAY_STATION = "RAILWAY_STATION", RAIL_FERRY = "RAIL_FERRY", RAPIDS = "RAPIDS", REAL_ESTATE_AGENCY_COMPANY = "REAL_ESTATE_AGENCY_COMPANY", REAL_ESTATE_AGENCY_SHOP = "REAL_ESTATE_AGENCY_SHOP", RECREATIONAL_SITE = "RECREATIONAL_SITE", RECREATIONAL_VEHICLE_DEALER = "RECREATIONAL_VEHICLE_DEALER", RECREATION_AREA = "RECREATION_AREA", RECYCLING_SHOP = "RECYCLING_SHOP", REEF = "REEF", REGIONS = "REGIONS", REPAIR_SHOP = "REPAIR_SHOP", RESEARCH_INSTITUTE = "RESEARCH_INSTITUTE", RESERVOIR = "RESERVOIR", RESIDENTIAL_ACCOMMODATION = "RESIDENTIAL_ACCOMMODATION", RESIDENTIAL_ESTATE = "RESIDENTIAL_ESTATE", RESORT = "RESORT", RESTAURANT = "RESTAURANT", RESTAURANT_AREA = "RESTAURANT_AREA", REST_AREA = "REST_AREA", REST_CAMPS = "REST_CAMPS", RETAIL_OUTLETS = "RETAIL_OUTLETS", RETIREMENT_COMMUNITY = "RETIREMENT_COMMUNITY", RIDGE = "RIDGE", RIVER_CROSSING = "RIVER_CROSSING", ROADSIDE = "ROADSIDE", ROAD_RESCUE_POINT = "ROAD_RESCUE_POINT", ROCKS = "ROCKS", ROCK_CLIMBING_TRAIL = "ROCK_CLIMBING_TRAIL", ROMANIAN_RESTAURANT = "ROMANIAN_RESTAURANT", ROUTE = "ROUTE", RUGBY_GROUND = "RUGBY_GROUND", RUSSIAN_RESTAURANT = "RUSSIAN_RESTAURANT", SALAD_BAR = "SALAD_BAR", SANDWICH_RESTAURANT = "SANDWICH_RESTAURANT", SAUNA_SOLARIUM_MASSAGE_CENTER = "SAUNA_SOLARIUM_MASSAGE_CENTER", SAVINGS_INSTITUTION = "SAVINGS_INSTITUTION", SAVOYAN_RESTAURANT = "SAVOYAN_RESTAURANT", SCANDINAVIAN_RESTAURANT = "SCANDINAVIAN_RESTAURANT", SCENIC_RIVER_AREA = "SCENIC_RIVER_AREA", SCHOOL = "SCHOOL", SCHOOL_BUS_SERVICE_COMPANY = "SCHOOL_BUS_SERVICE_COMPANY", SCIENCE_MUSEUM = "SCIENCE_MUSEUM", SCOTTISH_RESTAURANT = "SCOTTISH_RESTAURANT", SEAFOOD_RESTAURANT = "SEAFOOD_RESTAURANT", SEASHORE = "SEASHORE", SECURITY_GATE = "SECURITY_GATE", SECURITY_STORE = "SECURITY_STORE", SENIOR_HIGH_SCHOOL = "SENIOR_HIGH_SCHOOL", SERVICE_COMPANY = "SERVICE_COMPANY", SHANDONG_RESTAURANT = "SHANDONG_RESTAURANT", SHANGHAI_RESTAURANT = "SHANGHAI_RESTAURANT", SHINTO_SHRINE = "SHINTO_SHRINE", SHOOTING_RANGE = "SHOOTING_RANGE", SHOP = "SHOP", SHOPPING = "SHOPPING", SHOPPING_CENTER = "SHOPPING_CENTER", SHOPPING_SERVICE_CENTER = "SHOPPING_SERVICE_CENTER", SICHUAN_RESTAURANT = "SICHUAN_RESTAURANT", SICILIAN_RESTAURANT = "SICILIAN_RESTAURANT", SKI_LIFT = "SKI_LIFT", SKI_RESORT = "SKI_RESORT", SLAVIC_RESTAURANT = "SLAVIC_RESTAURANT", SLOVAK_RESTAURANT = "SLOVAK_RESTAURANT", SNACKS = "SNACKS", SNOOKER_POOL_BILLIARD_HALL = "SNOOKER_POOL_BILLIARD_HALL", SOCCER_FIELD = "SOCCER_FIELD", SOUL_FOOD_RESTAURANT = "SOUL_FOOD_RESTAURANT", SOUP_RESTAURANT = "SOUP_RESTAURANT", SPA = "SPA", SPANISH_RESTAURANT = "SPANISH_RESTAURANT", SPECIALIST_CLINIC = "SPECIALIST_CLINIC", SPECIALIZED_HOSPITAL = "SPECIALIZED_HOSPITAL", SPECIALTY_FOOD_STORE = "SPECIALTY_FOOD_STORE", SPECIALTY_STORE = "SPECIALTY_STORE", SPECIAL_SCHOOL = "SPECIAL_SCHOOL", SPORT = "SPORT", SPORTS_CENTER = "SPORTS_CENTER", SPORTS_CENTER_SUB = "SPORTS_CENTER_SUB", SPORTS_SCHOOL = "SPORTS_SCHOOL", SPORTS_STORE = "SPORTS_STORE", SQUASH_COURT = "SQUASH_COURT", STADIUM = "STADIUM", STAMP_SHOP = "STAMP_SHOP", STATION_ACCESS = "STATION_ACCESS", STATUE = "STATUE", STEAK_HOUSE = "STEAK_HOUSE", STOCK_EXCHANGE = "STOCK_EXCHANGE", STORE = "STORE", STREET_ADDRESS = "STREET_ADDRESS", SUDANESE_RESTAURANT = "SUDANESE_RESTAURANT", SUPERMARKET_HYPERMARKET = "SUPERMARKET_HYPERMARKET", SURINAMESE_RESTAURANT = "SURINAMESE_RESTAURANT", SUSHI_RESTAURANT = "SUSHI_RESTAURANT", SWEDISH_RESTAURANT = "SWEDISH_RESTAURANT", SWIMMING_POOL = "SWIMMING_POOL", SWISS_RESTAURANT = "SWISS_RESTAURANT", SYNAGOGUE = "SYNAGOGUE", SYRIAN_RESTAURANT = "SYRIAN_RESTAURANT", TABLE_TENNIS_HALL = "TABLE_TENNIS_HALL", TAILOR_SHOP = "TAILOR_SHOP", TAIWANESE_RESTAURANT = "TAIWANESE_RESTAURANT", TAKE_AWAY_RESTAURANT = "TAKE_AWAY_RESTAURANT", TAPAS_RESTAURANT = "TAPAS_RESTAURANT", TAXI_LIMOUSINE_SHUTTLE_SERVICE_COMPANY = "TAXI_LIMOUSINE_SHUTTLE_SERVICE_COMPANY", TAXI_STAND = "TAXI_STAND", TAX_SERVICE_COMPANY = "TAX_SERVICE_COMPANY", TEA_HOUSE = "TEA_HOUSE", TECHNICAL_SCHOOL = "TECHNICAL_SCHOOL", TELECOMMUNICATIONS_COMPANY = "TELECOMMUNICATIONS_COMPANY", TEMPLE = "TEMPLE", TENNIS_COURT = "TENNIS_COURT", TEPPANYAKKI_RESTAURANT = "TEPPANYAKKI_RESTAURANT", TERMINAL = "TERMINAL", THAI_RESTAURANT = "THAI_RESTAURANT", THEATER = "THEATER", THEATER_SUB = "THEATER_SUB", THEMED_SPORTS_HALL = "THEMED_SPORTS_HALL", THREE_STAR_HOTEL = "THREE_STAR_HOTEL", TIBETAN_RESTAURANT = "TIBETAN_RESTAURANT", TIRE_REPAIR_SHOP = "TIRE_REPAIR_SHOP", TOILET = "TOILET", TOLL_GATE = "TOLL_GATE", TOURISM = "TOURISM", TOURIST_INFORMATION_OFFICE = "TOURIST_INFORMATION_OFFICE", TOWER = "TOWER", TOWN = "TOWN", TOWNHOUSE_COMPLEX = "TOWNHOUSE_COMPLEX", TOWN_GOVERNMENT = "TOWN_GOVERNMENT", TOYS_AND_GAMES_STORE = "TOYS_AND_GAMES_STORE", TRAFFIC = "TRAFFIC", TRAFFIC_CONTROL_DEPARTMENT = "TRAFFIC_CONTROL_DEPARTMENT", TRAFFIC_LIGHT = "TRAFFIC_LIGHT", TRAFFIC_MANAGEMENT_BUREAU = "TRAFFIC_MANAGEMENT_BUREAU", TRAFFIC_SIGN = "TRAFFIC_SIGN", TRAFFIC_SIGNAL = "TRAFFIC_SIGNAL", TRAILHEAD = "TRAILHEAD", TRAIL_SYSTEM = "TRAIL_SYSTEM", TRAM_STOP = "TRAM_STOP", TRANSPORT = "TRANSPORT", TRANSPORTATION_COMPANY = "TRANSPORTATION_COMPANY", TRANSPORT__CENTER = "TRANSPORT__CENTER", TRAVEL_AGENCY = "TRAVEL_AGENCY", TRUCK_DEALER = "TRUCK_DEALER", TRUCK_PARKING_AREA = "TRUCK_PARKING_AREA", TRUCK_REPAIR_SHOP = "TRUCK_REPAIR_SHOP", TRUCK_STOP = "TRUCK_STOP", TRUCK_WASH = "TRUCK_WASH", TSUNAMI_ASSEMBLY_POINT = "TSUNAMI_ASSEMBLY_POINT", TUNISIAN_RESTAURANT = "TUNISIAN_RESTAURANT", TUNNEL = "TUNNEL", TURKISH_RESTAURANT = "TURKISH_RESTAURANT", UNRATED_HOTEL = "UNRATED_HOTEL", URUGUAYAN_RESTAURANT = "URUGUAYAN_RESTAURANT", USED_CAR_DEALER = "USED_CAR_DEALER", VALLEY = "VALLEY", VAN_DEALER = "VAN_DEALER", VARIETY_STORE = "VARIETY_STORE", VEGETARIAN_RESTAURANT = "VEGETARIAN_RESTAURANT", VENEZUELAN_RESTAURANT = "VENEZUELAN_RESTAURANT", VETERINARY_CLINIC = "VETERINARY_CLINIC", VIDEO_ARCADE_GAMING_ROOM = "VIDEO_ARCADE_GAMING_ROOM", VIETNAMESE_RESTAURANT = "VIETNAMESE_RESTAURANT", VILLA = "VILLA", VOCATIONAL_TRAINING_SCHOOL = "VOCATIONAL_TRAINING_SCHOOL", VOLCANIC_ERUPTION_ASSEMBLY_POINT = "VOLCANIC_ERUPTION_ASSEMBLY_POINT", WAREHOUSE_SUPERMARKET = "WAREHOUSE_SUPERMARKET", WATER_HOLE = "WATER_HOLE", WATER_SPORTS_CENTER = "WATER_SPORTS_CENTER", WEDDING_SERVICE_COMPANY = "WEDDING_SERVICE_COMPANY", WEIGH_SCALES = "WEIGH_SCALES", WEIGH_STATION = "WEIGH_STATION", WEIGH_STATION_SUB = "WEIGH_STATION_SUB", WELFARE_ORGANIZATION = "WELFARE_ORGANIZATION", WELL = "WELL", WELSH_RESTAURANT = "WELSH_RESTAURANT", WESTERN_RESTAURANT = "WESTERN_RESTAURANT", WILDERNESS_AREA = "WILDERNESS_AREA", WILDLIFE_PARK = "WILDLIFE_PARK", WINERY = "WINERY", WINERY_TOURIST = "WINERY_TOURIST", WINE_BAR = "WINE_BAR", WINE_SPIRITS_STORE = "WINE_SPIRITS_STORE", WINTER_SPORT_AREA = "WINTER_SPORT_AREA", YACHT_BASIN = "YACHT_BASIN", YOGURT_JUICE_BAR = "YOGURT_JUICE_BAR", ZOO = "ZOO", ZOO_ARBORETA_BOTANICAL_GARDEN = "ZOO_ARBORETA_BOTANICAL_GARDEN", }
the_stack
import {Component, Directive} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('@angular/common integration', () => { describe('NgForOf', () => { @Directive({selector: '[dir]'}) class MyDirective { } @Component({selector: 'app-child', template: '<div dir>comp text</div>'}) class ChildComponent { } @Component({selector: 'app-root', template: ''}) class AppComponent { items: string[] = ['first', 'second']; } beforeEach(() => { TestBed.configureTestingModule({declarations: [AppComponent, ChildComponent, MyDirective]}); }); it('should update a loop', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items">{{item}}</li></ul>'); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['first', 'second']); // change detection cycle, no model changes fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['first', 'second']); // remove the last item const items = fixture.componentInstance.items; items.length = 1; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['first']); // change an item items[0] = 'one'; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['one']); // add an item items.push('two'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['one', 'two']); }); it('should support ngForOf context variables', () => { TestBed.overrideTemplate( AppComponent, '<ul><li *ngFor="let item of items; index as myIndex; count as myCount">{{myIndex}} of {{myCount}}: {{item}}</li></ul>'); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); let listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual(['0 of 2: first', '1 of 2: second']); // add an item in the middle const items = fixture.componentInstance.items; items.splice(1, 0, 'middle'); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.map(li => li.textContent)).toEqual([ '0 of 3: first', '1 of 3: middle', '2 of 3: second' ]); }); it('should instantiate directives inside directives properly in an ngFor', () => { TestBed.overrideTemplate(AppComponent, '<app-child *ngFor="let item of items"></app-child>'); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const children = fixture.debugElement.queryAll(By.directive(ChildComponent)); // expect 2 children, each one with a directive expect(children.length).toBe(2); expect(children.map(child => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>' ]); let directive = children[0].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); directive = children[1].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); // add an item const items = fixture.componentInstance.items; items.push('third'); fixture.detectChanges(); const childrenAfterAdd = fixture.debugElement.queryAll(By.directive(ChildComponent)); expect(childrenAfterAdd.length).toBe(3); expect(childrenAfterAdd.map(child => child.nativeElement.innerHTML)).toEqual([ '<div dir="">comp text</div>', '<div dir="">comp text</div>', '<div dir="">comp text</div>' ]); directive = childrenAfterAdd[2].query(By.directive(MyDirective)); expect(directive).not.toBeNull(); }); it('should retain parent view listeners when the NgFor destroy views', () => { @Component({ selector: 'app-toggle', template: `<button (click)="toggle()">Toggle List</button> <ul> <li *ngFor="let item of items">{{item}}</li> </ul>` }) class ToggleComponent { private _data: number[] = [1, 2, 3]; items: number[] = []; toggle() { if (this.items.length) { this.items = []; } else { this.items = this._data; } } } TestBed.configureTestingModule({declarations: [ToggleComponent]}); const fixture = TestBed.createComponent(ToggleComponent); fixture.detectChanges(); // no elements in the list let listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(0); // this will fill the list fixture.componentInstance.toggle(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); expect(listItems.map(li => li.textContent)).toEqual(['1', '2', '3']); // now toggle via the button const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(0); // toggle again button.click(); fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(3); }); it('should support multiple levels of embedded templates', () => { @Component({ selector: 'app-multi', template: `<ul> <li *ngFor="let row of items"> <span *ngFor="let cell of row.data">{{cell}} - {{ row.value }} - {{ items.length }}</span> </li> </ul>` }) class MultiLevelComponent { items: any[] = [{data: ['1', '2'], value: 'first'}, {data: ['3', '4'], value: 'second'}]; } TestBed.configureTestingModule({declarations: [MultiLevelComponent]}); const fixture = TestBed.createComponent(MultiLevelComponent); fixture.detectChanges(); // change detection cycle, no model changes let listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(2); let spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual(['1 - first - 2', '2 - first - 2']); spanItems = Array.from(listItems[1].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual(['3 - second - 2', '4 - second - 2']); // remove the last item const items = fixture.componentInstance.items; items.length = 1; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(1); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual(['1 - first - 1', '2 - first - 1']); // change an item items[0].data[0] = 'one'; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(1); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual(['one - first - 1', '2 - first - 1']); // add an item items[1] = {data: ['three', '4'], value: 'third'}; fixture.detectChanges(); listItems = Array.from((fixture.nativeElement as HTMLUListElement).querySelectorAll('li')); expect(listItems.length).toBe(2); spanItems = Array.from(listItems[0].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual(['one - first - 2', '2 - first - 2']); spanItems = Array.from(listItems[1].querySelectorAll('span')); expect(spanItems.map(span => span.textContent)).toEqual([ 'three - third - 2', '4 - third - 2' ]); }); it('should support multiple levels of embedded templates with listeners', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let row of items"> <p *ngFor="let cell of row.data"> <span (click)="onClick(row.value, name)"></span> {{ row.value }} - {{ name }} </p> </div>` }) class MultiLevelWithListenerComponent { items: any[] = [{data: ['1'], value: 'first'}]; name = 'app'; events: string[] = []; onClick(value: string, name: string) { this.events.push(value, name); } } TestBed.configureTestingModule({declarations: [MultiLevelWithListenerComponent]}); const fixture = TestBed.createComponent(MultiLevelWithListenerComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('p'); expect(elements.length).toBe(1); expect(elements[0].innerHTML).toBe('<span></span> first - app '); const span: HTMLSpanElement = fixture.nativeElement.querySelector('span'); span.click(); expect(fixture.componentInstance.events).toEqual(['first', 'app']); fixture.componentInstance.name = 'new name'; fixture.detectChanges(); expect(elements[0].innerHTML).toBe('<span></span> first - new name '); span.click(); expect(fixture.componentInstance.events).toEqual(['first', 'app', 'first', 'new name']); }); it('should support skipping contexts', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let row of items"> <div *ngFor="let cell of row"> <span *ngFor="let span of cell.data">{{ cell.value }} - {{ name }}</span> </div> </div>` }) class SkippingContextComponent { name = 'app'; items: any[] = [ [ // row {value: 'one', data: ['1', '2']} // cell ], [{value: 'two', data: ['3', '4']}] ]; } TestBed.configureTestingModule({declarations: [SkippingContextComponent]}); const fixture = TestBed.createComponent(SkippingContextComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('span'); expect(elements.length).toBe(4); expect(elements[0].textContent).toBe('one - app'); expect(elements[1].textContent).toBe('one - app'); expect(elements[2].textContent).toBe('two - app'); expect(elements[3].textContent).toBe('two - app'); fixture.componentInstance.name = 'other'; fixture.detectChanges(); expect(elements[0].textContent).toBe('one - other'); expect(elements[1].textContent).toBe('one - other'); expect(elements[2].textContent).toBe('two - other'); expect(elements[3].textContent).toBe('two - other'); }); it('should support context for 9+ levels of embedded templates', () => { @Component({ selector: 'app-multi', template: `<div *ngFor="let item0 of items"> <span *ngFor="let item1 of item0.data"> <span *ngFor="let item2 of item1.data"> <span *ngFor="let item3 of item2.data"> <span *ngFor="let item4 of item3.data"> <span *ngFor="let item5 of item4.data"> <span *ngFor="let item6 of item5.data"> <span *ngFor="let item7 of item6.data"> <span *ngFor="let item8 of item7.data">{{ item8 }}.{{ item7.value }}.{{ item6.value }}.{{ item5.value }}.{{ item4.value }}.{{ item3.value }}.{{ item2.value }}.{{ item1.value }}.{{ item0.value }}.{{ value }}</span> </span> </span> </span> </span> </span> </span> </span> </div>` }) class NineLevelsComponent { value = 'App'; items: any[] = [ { // item0 data: [{ // item1 data: [{ // item2 data: [{ // item3 data: [{ // item4 data: [{ // item5 data: [{ // item6 data: [{ // item7 data: [ '1', '2' // item8 ], value: 'h' }], value: 'g' }], value: 'f' }], value: 'e' }], value: 'd' }], value: 'c' }], value: 'b' }], value: 'a' }, { // item0 data: [{ // item1 data: [{ // item2 data: [{ // item3 data: [{ // item4 data: [{ // item5 data: [{ // item6 data: [{ // item7 data: [ '3', '4' // item8 ], value: 'H' }], value: 'G' }], value: 'F' }], value: 'E' }], value: 'D' }], value: 'C' }], value: 'B' }], value: 'A' } ]; } TestBed.configureTestingModule({declarations: [NineLevelsComponent]}); const fixture = TestBed.createComponent(NineLevelsComponent); fixture.detectChanges(); const divItems = (fixture.nativeElement as HTMLElement).querySelectorAll('div'); expect(divItems.length).toBe(2); // 2 outer loops let spanItems = divItems[0].querySelectorAll('span > span > span > span > span > span > span > span'); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('1.h.g.f.e.d.c.b.a.App'); expect(spanItems[1].textContent).toBe('2.h.g.f.e.d.c.b.a.App'); spanItems = divItems[1].querySelectorAll('span > span > span > span > span > span > span > span'); expect(spanItems.length).toBe(2); // 2 inner elements expect(spanItems[0].textContent).toBe('3.H.G.F.E.D.C.B.A.App'); expect(spanItems[1].textContent).toBe('4.H.G.F.E.D.C.B.A.App'); }); }); describe('ngIf', () => { it('should support sibling ngIfs', () => { @Component({ selector: 'app-multi', template: ` <div *ngIf="showing">{{ valueOne }}</div> <div *ngIf="showing">{{ valueTwo }}</div> ` }) class SimpleConditionComponent { showing = true; valueOne = 'one'; valueTwo = 'two'; } TestBed.configureTestingModule({declarations: [SimpleConditionComponent]}); const fixture = TestBed.createComponent(SimpleConditionComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(2); expect(elements[0].textContent).toBe('one'); expect(elements[1].textContent).toBe('two'); fixture.componentInstance.valueOne = '$$one$$'; fixture.componentInstance.valueTwo = '$$two$$'; fixture.detectChanges(); expect(elements[0].textContent).toBe('$$one$$'); expect(elements[1].textContent).toBe('$$two$$'); }); it('should handle nested ngIfs with no intermediate context vars', () => { @Component({ selector: 'app-multi', template: `<div *ngIf="showing"> <div *ngIf="outerShowing"> <div *ngIf="innerShowing">{{ name }}</div> </div> </div> ` }) class NestedConditionsComponent { showing = true; outerShowing = true; innerShowing = true; name = 'App name'; } TestBed.configureTestingModule({declarations: [NestedConditionsComponent]}); const fixture = TestBed.createComponent(NestedConditionsComponent); fixture.detectChanges(); const elements = fixture.nativeElement.querySelectorAll('div'); expect(elements.length).toBe(3); expect(elements[2].textContent).toBe('App name'); fixture.componentInstance.name = 'Other name'; fixture.detectChanges(); expect(elements[2].textContent).toBe('Other name'); }); }); describe('NgTemplateOutlet', () => { it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-template [ngTemplateOutlet]="showing ? tpl : null"></ng-template> ` }) class EmbeddedViewsComponent { showing = false; } TestBed.configureTestingModule({declarations: [EmbeddedViewsComponent]}); const fixture = TestBed.createComponent(EmbeddedViewsComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); it('should create and remove embedded views', () => { @Component({ selector: 'app-multi', template: `<ng-template #tpl>from tpl</ng-template> <ng-container [ngTemplateOutlet]="showing ? tpl : null"></ng-container> ` }) class NgContainerComponent { showing = false; } TestBed.configureTestingModule({declarations: [NgContainerComponent]}); const fixture = TestBed.createComponent(NgContainerComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); fixture.componentInstance.showing = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('from tpl'); fixture.componentInstance.showing = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toBe('from tpl'); }); }); });
the_stack
import { PortMap, PortRange } from '../src/compose/ports'; import { expect } from 'chai'; // Force cast `PortMap` as a public version so we can test it const PortMapPublic = (PortMap as any) as new ( portStrOrObj: string | PortRange, ) => PortMap; describe('Ports', function () { describe('Port string parsing', function () { it('should correctly parse a port string without a range', function () { expect(new PortMapPublic('80')).to.deep.equal( new PortMapPublic({ internalStart: 80, internalEnd: 80, externalStart: 80, externalEnd: 80, protocol: 'tcp', host: '', }), ); expect(new PortMapPublic('80:80')).to.deep.equal( new PortMapPublic({ internalStart: 80, internalEnd: 80, externalStart: 80, externalEnd: 80, protocol: 'tcp', host: '', }), ); }); it('should correctly parse a port string without an external range', () => expect(new PortMapPublic('80-90')).to.deep.equal( new PortMapPublic({ internalStart: 80, internalEnd: 90, externalStart: 80, externalEnd: 90, protocol: 'tcp', host: '', }), )); it('should correctly parse a port string with a range', () => expect(new PortMapPublic('80-100:100-120')).to.deep.equal( new PortMapPublic({ internalStart: 100, internalEnd: 120, externalStart: 80, externalEnd: 100, protocol: 'tcp', host: '', }), )); it('should correctly parse a protocol', function () { expect(new PortMapPublic('80/udp')).to.deep.equal( new PortMapPublic({ internalStart: 80, internalEnd: 80, externalStart: 80, externalEnd: 80, protocol: 'udp', host: '', }), ); expect(new PortMapPublic('80:80/udp')).to.deep.equal( new PortMapPublic({ internalStart: 80, internalEnd: 80, externalStart: 80, externalEnd: 80, protocol: 'udp', host: '', }), ); expect(new PortMapPublic('80-90:100-110/udp')).to.deep.equal( new PortMapPublic({ internalStart: 100, internalEnd: 110, externalStart: 80, externalEnd: 90, protocol: 'udp', host: '', }), ); }); it('should throw when the port string is incorrect', () => expect(() => new PortMapPublic('80-90:80-85')).to.throw); }); describe('toDockerOpts', function () { it('should correctly generate docker options', () => expect(new PortMapPublic('80').toDockerOpts()).to.deep.equal({ exposedPorts: { '80/tcp': {}, }, portBindings: { '80/tcp': [{ HostIp: '', HostPort: '80' }], }, })); it('should correctly generate docker options for a port range', () => expect(new PortMapPublic('80-85').toDockerOpts()).to.deep.equal({ exposedPorts: { '80/tcp': {}, '81/tcp': {}, '82/tcp': {}, '83/tcp': {}, '84/tcp': {}, '85/tcp': {}, }, portBindings: { '80/tcp': [{ HostIp: '', HostPort: '80' }], '81/tcp': [{ HostIp: '', HostPort: '81' }], '82/tcp': [{ HostIp: '', HostPort: '82' }], '83/tcp': [{ HostIp: '', HostPort: '83' }], '84/tcp': [{ HostIp: '', HostPort: '84' }], '85/tcp': [{ HostIp: '', HostPort: '85' }], }, })); }); describe('fromDockerOpts', function () { it('should correctly detect a port range', () => expect( PortMap.fromDockerOpts({ '100/tcp': [{ HostIp: '123', HostPort: '200' }], '101/tcp': [{ HostIp: '123', HostPort: '201' }], '102/tcp': [{ HostIp: '123', HostPort: '202' }], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 102, externalStart: 200, externalEnd: 202, protocol: 'tcp', host: '123', }), ])); it('should correctly split ports into ranges', () => expect( PortMap.fromDockerOpts({ '100/tcp': [{ HostIp: '123', HostPort: '200' }], '101/tcp': [{ HostIp: '123', HostPort: '201' }], '105/tcp': [{ HostIp: '123', HostPort: '205' }], '106/tcp': [{ HostIp: '123', HostPort: '206' }], '110/tcp': [{ HostIp: '123', HostPort: '210' }], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 101, externalStart: 200, externalEnd: 201, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 105, internalEnd: 106, externalStart: 205, externalEnd: 206, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 110, internalEnd: 110, externalStart: 210, externalEnd: 210, protocol: 'tcp', host: '123', }), ])); it('should correctly consider internal and external ports', () => expect( PortMap.fromDockerOpts({ '100/tcp': [{ HostIp: '123', HostPort: '200' }], '101/tcp': [{ HostIp: '123', HostPort: '101' }], '102/tcp': [{ HostIp: '123', HostPort: '202' }], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 100, externalStart: 200, externalEnd: 200, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 101, internalEnd: 101, externalStart: 101, externalEnd: 101, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 102, internalEnd: 102, externalStart: 202, externalEnd: 202, protocol: 'tcp', host: '123', }), ])); it('should consider the host when generating ranges', () => expect( PortMap.fromDockerOpts({ '100/tcp': [{ HostIp: '123', HostPort: '200' }], '101/tcp': [{ HostIp: '456', HostPort: '201' }], '102/tcp': [{ HostIp: '456', HostPort: '202' }], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 100, externalStart: 200, externalEnd: 200, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 101, internalEnd: 102, externalStart: 201, externalEnd: 202, protocol: 'tcp', host: '456', }), ])); it('should consider the protocol when generating ranges', () => expect( PortMap.fromDockerOpts({ '100/tcp': [{ HostIp: '123', HostPort: '200' }], '101/udp': [{ HostIp: '123', HostPort: '201' }], '102/udp': [{ HostIp: '123', HostPort: '202' }], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 100, externalStart: 200, externalEnd: 200, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 101, internalEnd: 102, externalStart: 201, externalEnd: 202, protocol: 'udp', host: '123', }), ])); it('should correctly detect multiple hosts ports on an internal port', () => expect( PortMap.fromDockerOpts({ '100/tcp': [ { HostIp: '123', HostPort: '200' }, { HostIp: '123', HostPort: '201' }, ], }), ).to.deep.equal([ new PortMapPublic({ internalStart: 100, internalEnd: 100, externalStart: 200, externalEnd: 200, protocol: 'tcp', host: '123', }), new PortMapPublic({ internalStart: 100, internalEnd: 100, externalStart: 201, externalEnd: 201, protocol: 'tcp', host: '123', }), ])); }); describe('Running container comparison', () => it('should not consider order when comparing current and target state', function () { const portBindings = require('./data/ports/not-ascending/port-bindings.json'); const compose = require('./data/ports/not-ascending/compose.json'); const portMapsCurrent = PortMap.fromDockerOpts(portBindings); const portMapsTarget = PortMap.fromComposePorts(compose.ports); expect(portMapsTarget).to.deep.equal(portMapsCurrent); })); describe('fromComposePorts', () => it('should normalise compose ports', () => expect( PortMap.fromComposePorts(['80:80', '81:81', '82:82']), ).to.deep.equal([new PortMapPublic('80-82')]))); describe('normalisePortMaps', function () { it('should correctly normalise PortMap lists', function () { expect( PortMap.normalisePortMaps([ new PortMapPublic('80:90'), new PortMapPublic('81:91'), ]), ).to.deep.equal([new PortMapPublic('80-81:90-91')]); expect( PortMap.normalisePortMaps([ new PortMapPublic('80:90'), new PortMapPublic('81:91'), new PortMapPublic('82:92'), new PortMapPublic('83:93'), new PortMapPublic('84:94'), new PortMapPublic('85:95'), new PortMapPublic('86:96'), new PortMapPublic('87:97'), new PortMapPublic('88:98'), new PortMapPublic('89:99'), new PortMapPublic('90:100'), ]), ).to.deep.equal([new PortMapPublic('80-90:90-100')]); expect(PortMap.normalisePortMaps([])).to.deep.equal([]); }); it('should correctly consider protocols', function () { expect( PortMap.normalisePortMaps([ new PortMapPublic('80:90'), new PortMapPublic('81:91/udp'), ]), ).to.deep.equal([ new PortMapPublic('80:90'), new PortMapPublic('81:91/udp'), ]); expect( PortMap.normalisePortMaps([ new PortMapPublic('80:90'), new PortMapPublic('100:110/udp'), new PortMapPublic('81:91'), ]), ).to.deep.equal([ new PortMapPublic('80-81:90-91'), new PortMapPublic('100:110/udp'), ]); // This shouldn't ever be provided, but it shows the algorithm // working properly expect( PortMap.normalisePortMaps([ new PortMapPublic('80:90'), new PortMapPublic('81:91/udp'), new PortMapPublic('81:91'), ]), ).to.deep.equal([ new PortMapPublic('80-81:90-91'), new PortMapPublic('81:91/udp'), ]); }); it('should correctly consider hosts', function () { expect( PortMap.normalisePortMaps([ new PortMapPublic('127.0.0.1:80:80'), new PortMapPublic('81:81'), ]), ).to.deep.equal([ new PortMapPublic('127.0.0.1:80:80'), new PortMapPublic('81:81'), ]); expect( PortMap.normalisePortMaps([ new PortMapPublic('127.0.0.1:80:80'), new PortMapPublic('127.0.0.1:81:81'), ]), ).to.deep.equal([new PortMapPublic('127.0.0.1:80-81:80-81')]); }); }); });
the_stack
require('./split-tile.css'); import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as Q from 'q'; import { SvgIcon } from '../svg-icon/svg-icon'; import { STRINGS, CORE_ITEM_WIDTH, CORE_ITEM_GAP } from '../../config/constants'; import { Stage, Clicker, Essence, VisStrategy, DataCube, Filter, SplitCombine, Dimension, DragPosition } from '../../../common/models/index'; import { findParentWithClass, setDragGhost, transformStyle, getXFromEvent, isInside, uniqueId, classNames } from '../../utils/dom/dom'; import { getMaxItems, SECTION_WIDTH } from '../../utils/pill-tile/pill-tile'; import { DragManager } from '../../utils/drag-manager/drag-manager'; import { FancyDragIndicator } from '../fancy-drag-indicator/fancy-drag-indicator'; import { SplitMenu } from '../split-menu/split-menu'; import { BubbleMenu } from '../bubble-menu/bubble-menu'; const SPLIT_CLASS_NAME = 'split'; export interface SplitTileProps extends React.Props<any> { clicker: Clicker; essence: Essence; menuStage: Stage; getUrlPrefix?: () => string; } export interface SplitTileState { SplitMenuAsync?: typeof SplitMenu; menuOpenOn?: Element; menuDimension?: Dimension; menuSplit?: SplitCombine; dragPosition?: DragPosition; overflowMenuOpenOn?: Element; maxItems?: number; menuInside?: Element; } export class SplitTile extends React.Component<SplitTileProps, SplitTileState> { private overflowMenuId: string; private overflowMenuDeferred: Q.Deferred<Element>; constructor() { super(); this.overflowMenuId = uniqueId('overflow-menu-'); this.state = { SplitMenuAsync: null, menuOpenOn: null, menuDimension: null, dragPosition: null, maxItems: null }; } componentDidMount() { require.ensure(['../split-menu/split-menu'], (require) => { this.setState({ SplitMenuAsync: require('../split-menu/split-menu').SplitMenu }); }, 'split-menu'); } componentWillReceiveProps(nextProps: SplitTileProps) { const { menuStage, essence } = nextProps; var { splits } = essence; if (menuStage) { var newMaxItems = getMaxItems(menuStage.width, splits.toArray().length); if (newMaxItems !== this.state.maxItems) { this.setState({ menuOpenOn: null, menuDimension: null, overflowMenuOpenOn: null, maxItems: newMaxItems }); } } } componentDidUpdate() { var { overflowMenuOpenOn } = this.state; if (overflowMenuOpenOn) { var overflowMenu = this.getOverflowMenu(); if (overflowMenu) this.overflowMenuDeferred.resolve(overflowMenu); } } selectDimensionSplit(dimension: Dimension, split: SplitCombine, e: MouseEvent) { var target = findParentWithClass(e.target as Element, SPLIT_CLASS_NAME); this.openMenu(dimension, split, target); } openMenu(dimension: Dimension, split: SplitCombine, target: Element) { var { menuOpenOn } = this.state; if (menuOpenOn === target) { this.closeMenu(); return; } var overflowMenu = this.getOverflowMenu(); var menuInside: Element = null; if (overflowMenu && isInside(target, overflowMenu)) { menuInside = overflowMenu; } this.setState({ menuOpenOn: target, menuDimension: dimension, menuSplit: split, menuInside }); } closeMenu() { var { menuOpenOn } = this.state; if (!menuOpenOn) return; this.setState({ menuOpenOn: null, menuDimension: null, menuInside: null, menuSplit: null }); } getOverflowMenu(): Element { return document.getElementById(this.overflowMenuId); } openOverflowMenu(target: Element): Q.Promise<any> { if (!target) return Q(null); var { overflowMenuOpenOn } = this.state; if (overflowMenuOpenOn === target) { this.closeOverflowMenu(); return Q(null); } this.overflowMenuDeferred = Q.defer() as Q.Deferred<Element>; this.setState({ overflowMenuOpenOn: target }); return this.overflowMenuDeferred.promise; } closeOverflowMenu() { var { overflowMenuOpenOn } = this.state; if (!overflowMenuOpenOn) return; this.setState({ overflowMenuOpenOn: null }); } removeSplit(split: SplitCombine, e: MouseEvent) { var { clicker } = this.props; clicker.removeSplit(split, VisStrategy.FairGame); this.closeMenu(); this.closeOverflowMenu(); e.stopPropagation(); } dragStart(dimension: Dimension, split: SplitCombine, splitIndex: number, e: DragEvent) { var { essence, getUrlPrefix } = this.props; var dataTransfer = e.dataTransfer; dataTransfer.effectAllowed = 'all'; if (getUrlPrefix) { var newUrl = essence.changeSplit(SplitCombine.fromExpression(dimension.expression), VisStrategy.FairGame).getURL(getUrlPrefix()); dataTransfer.setData("text/url-list", newUrl); dataTransfer.setData("text/plain", newUrl); } DragManager.setDragSplit(split, 'filter-tile'); DragManager.setDragDimension(dimension, 'filter-tile'); setDragGhost(dataTransfer, dimension.title); this.closeMenu(); this.closeOverflowMenu(); } calculateDragPosition(e: DragEvent): DragPosition { const { essence } = this.props; var numItems = essence.splits.length(); var rect = ReactDOM.findDOMNode(this.refs['items']).getBoundingClientRect(); var x = getXFromEvent(e); var offset = x - rect.left; return DragPosition.calculateFromOffset(offset, numItems, CORE_ITEM_WIDTH, CORE_ITEM_GAP); } canDrop(e: DragEvent): boolean { return Boolean(DragManager.getDragSplit() || DragManager.getDragDimension()); } dragEnter(e: DragEvent) { if (!this.canDrop(e)) return; e.preventDefault(); this.setState({ dragPosition: this.calculateDragPosition(e) }); } dragOver(e: DragEvent) { if (!this.canDrop(e)) return; e.dataTransfer.dropEffect = 'move'; e.preventDefault(); var dragPosition = this.calculateDragPosition(e); if (dragPosition.equals(this.state.dragPosition)) return; this.setState({ dragPosition }); } dragLeave(e: DragEvent) { if (!this.canDrop(e)) return; this.setState({ dragPosition: null }); } drop(e: DragEvent) { if (!this.canDrop(e)) return; e.preventDefault(); var { clicker, essence } = this.props; var { maxItems } = this.state; var { splits } = essence; var newSplitCombine: SplitCombine = null; if (DragManager.getDragSplit()) { newSplitCombine = DragManager.getDragSplit(); } else if (DragManager.getDragDimension()) { newSplitCombine = SplitCombine.fromExpression(DragManager.getDragDimension().expression); } if (newSplitCombine) { var dragPosition = this.calculateDragPosition(e); if (dragPosition.replace === maxItems) { dragPosition = new DragPosition({ insert: dragPosition.replace }); } if (dragPosition.isReplace()) { clicker.changeSplits(splits.replaceByIndex(dragPosition.replace, newSplitCombine), VisStrategy.FairGame); } else { clicker.changeSplits(splits.insertByIndex(dragPosition.insert, newSplitCombine), VisStrategy.FairGame); } } this.setState({ dragPosition: null }); } // This will be called externally splitMenuRequest(dimension: Dimension) { var { splits } = this.props.essence; var split = splits.findSplitForDimension(dimension); if (!split) return; var targetRef = this.refs[dimension.name]; if (!targetRef) return; var target = ReactDOM.findDOMNode(targetRef); if (!target) return; this.openMenu(dimension, split, target); } overflowButtonTarget(): Element { return ReactDOM.findDOMNode(this.refs['overflow']); } overflowButtonClick() { this.openOverflowMenu(this.overflowButtonTarget()); }; renderMenu(): JSX.Element { var { essence, clicker, menuStage } = this.props; var { SplitMenuAsync, menuOpenOn, menuDimension, menuSplit, menuInside, overflowMenuOpenOn } = this.state; if (!SplitMenuAsync || !menuDimension) return null; var onClose = this.closeMenu.bind(this); return <SplitMenuAsync clicker={clicker} essence={essence} containerStage={overflowMenuOpenOn ? null : menuStage} openOn={menuOpenOn} dimension={menuDimension} split={menuSplit} onClose={onClose} inside={menuInside} />; } renderOverflowMenu(items: SplitCombine[]): JSX.Element { var { overflowMenuOpenOn } = this.state; if (!overflowMenuOpenOn) return null; var segmentHeight = 29 + CORE_ITEM_GAP; var itemY = CORE_ITEM_GAP; var filterItems = items.map((item, i) => { var style = transformStyle(0, itemY); itemY += segmentHeight; return this.renderSplit(item, style, i); }); return <BubbleMenu className="overflow-menu" id={this.overflowMenuId} direction="down" stage={Stage.fromSize(208, itemY)} fixedSize={true} openOn={overflowMenuOpenOn} onClose={this.closeOverflowMenu.bind(this)} > {filterItems} </BubbleMenu>; } renderOverflow(items: SplitCombine[], itemX: number): JSX.Element { var { essence } = this.props; var { dataCube } = essence; var style = transformStyle(itemX, 0); return <div className={classNames('overflow', { 'all-continuous': items.every(item => item.getDimension(dataCube.dimensions).isContinuous()) })} ref="overflow" key="overflow" style={style} onClick={this.overflowButtonClick.bind(this)} > <div className="count">{'+' + items.length}</div> {this.renderOverflowMenu(items)} </div>; } renderSplit(split: SplitCombine, style: React.CSSProperties, i: number) { var { essence } = this.props; var { menuDimension } = this.state; var { dataCube } = essence; var dimension = split.getDimension(dataCube.dimensions); if (!dimension) throw new Error('dimension not found'); var dimensionName = dimension.name; var classNames = [ SPLIT_CLASS_NAME, 'type-' + dimension.className ]; if (dimension === menuDimension) classNames.push('selected'); return <div className={classNames.join(' ')} key={split.toKey()} ref={dimensionName} draggable={true} onClick={this.selectDimensionSplit.bind(this, dimension, split)} onDragStart={this.dragStart.bind(this, dimension, split, i)} style={style} > <div className="reading">{split.getTitle(dataCube.dimensions)}</div> <div className="remove" onClick={this.removeSplit.bind(this, split)}> <SvgIcon svg={require('../../icons/x.svg')}/> </div> </div>; } render() { var { essence } = this.props; var { dragPosition, maxItems } = this.state; var { splits } = essence; var splitsArray = splits.toArray(); var itemX = 0; var splitItems = splitsArray.slice(0, maxItems).map((split, i) => { var style = transformStyle(itemX, 0); itemX += SECTION_WIDTH; return this.renderSplit(split, style, i); }, this); var overflowItems = splitsArray.slice(maxItems); if (overflowItems.length > 0) { var overFlowStart = splitItems.length * SECTION_WIDTH; splitItems.push(this.renderOverflow(overflowItems, overFlowStart)); } return <div className="split-tile" onDragEnter={this.dragEnter.bind(this)} > <div className="title">{STRINGS.split}</div> <div className="items" ref="items"> {splitItems} </div> {dragPosition ? <FancyDragIndicator dragPosition={dragPosition}/> : null} {dragPosition ? <div className="drag-mask" onDragOver={this.dragOver.bind(this)} onDragLeave={this.dragLeave.bind(this)} onDragExit={this.dragLeave.bind(this)} onDrop={this.drop.bind(this)} /> : null} {this.renderMenu()} </div>; } }
the_stack
import * as CodeMirror from 'codemirror'; import {AfterViewInit, Component, EventEmitter, forwardRef, Input, OnDestroy, Output, ViewChild,} from '@angular/core'; import {NG_VALUE_ACCESSOR} from '@angular/forms'; import {isUndefined} from 'util'; /** * CodeMirror component * Usage : * <codemirror [(ngModel)]="data" [config]="{...}"></codemirror> */ @Component({ selector: 'codemirror', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CodemirrorComponent), multi: true } ], template: `<textarea #host></textarea>`, }) export class CodemirrorComponent implements AfterViewInit, OnDestroy { @Input() config; @Output() change = new EventEmitter(); @Output() focus = new EventEmitter(); @Output() blur = new EventEmitter(); @Output() cursorActivity = new EventEmitter(); @ViewChild('host') host; @Output() instance = null; _value = ''; public codeMirror: any; /** * Constructor */ constructor() { } get value() { return this._value; } @Input() set value(v) { if (v !== this._value) { this._value = v; this.onChange(v); } } /** * On component destroy */ ngOnDestroy() { } /** * On component view init */ ngAfterViewInit() { this.config = this.config || {}; this.codemirrorInit(this.config); } /** * Initialize codemirror */ codemirrorInit(config) { // CodeMirror.k.default["Shift-Tab"] = "indentLess"; // CodeMirror.keyMap.default["Tab"] = "indentMore"; this.instance = CodeMirror.fromTextArea(this.host.nativeElement, config); this.instance.setValue(this._value); this.instance.on('change', () => { this.updateValue(this.instance.getValue()); }); this.instance.on('focus', (instance, event) => { this.focus.emit({instance, event}); }); this.instance.on('cursorActivity', (instance) => { this.cursorActivity.emit({instance}); }); this.instance.on('blur', (instance, event) => { this.blur.emit({instance, event}); }); } /** * Value update process */ updateValue(value) { this.value = value; this.onTouched(); this.change.emit(value); } /** * Implements ControlValueAccessor */ writeValue(value) { this._value = value || ''; if (this.instance) { this.instance.setValue(this._value); } } onChange(_) { } onTouched() { } registerOnChange(fn) { this.onChange = fn; } registerOnTouched(fn) { this.onTouched = fn; } public setText(text: string): void { if (text === null || text === undefined) { text = ''; } this.writeValue(text); } public insert(text: string): void { if (text === null || text === undefined) { text = ''; } const $scrollContainer = $('.CodeMirror-scroll'); const scrollHeight = $scrollContainer.scrollTop(); let temp = text; const line: number = this.instance.doc.getCursor().line; const ch: number = this.instance.doc.getCursor().ch; const lines: any[] = this.getLines(); let beforeText: string = this.instance.doc.getRange({line: 0, ch: 0}, {line: line, ch: ch}); let afterText: string = this.instance.doc.getRange({line: line, ch: ch}, {line: lines.length, ch: 0}); // 현재 커서 위치 이전 마지막 단어가 세이콜론이 아닐 경우, 현재 커서 위치 이후 세미콜론이 존재 할경우 if (beforeText.trim() !== '' && beforeText.trim().substr(beforeText.trim().length - 1) !== ';' && afterText.search(';') !== -1) { const tempTextArr = afterText.split(';'); // 이전 내용 붙이기 beforeText += (tempTextArr[0] + ';'); afterText = ''; for (let idx: number = 0; idx < tempTextArr.length; idx++) { if (idx !== 0) { if (idx === tempTextArr.length - 1) { afterText += (tempTextArr[idx]); break; } afterText += (tempTextArr[idx] + ';'); } } } // end if if (beforeText === '') { if (text.indexOf('\n') > -1) { temp = beforeText + temp.replace('\n', '') + afterText; } else { temp = beforeText + temp + afterText; } this.writeValue(temp); this.instance.setCursor({line: line + 1, ch: ch + text.length}); } else { temp = beforeText + temp + afterText; this.writeValue(temp); if (text.indexOf('\n') > -1) { // this.instance.setCursor({ line: line + 1, ch: ch + text.length }); this.instance.setCursor({line: beforeText.split('\n').length, ch: ch + text.length}); } else { this.instance.setCursor({line: line, ch: ch + text.length}); } } $scrollContainer.scrollTop(scrollHeight); this.instance.focus(); } /** * insert column * @param text */ public insertColumn(text: string): void { if (text === null || text === undefined) { text = ''; } let temp = text; const line: number = this.instance.doc.getCursor().line; const ch: number = this.instance.doc.getCursor().ch; const lines: any[] = this.getLines(); const beforeText: string = this.instance.doc.getRange({line: 0, ch: 0}, {line: line, ch: ch}); const afterText: string = this.instance.doc.getRange({line: line, ch: ch}, {line: lines.length, ch: 0}); if (beforeText === '') { if (text.indexOf('\n') > -1) { temp = beforeText + temp.replace('\n', '') + afterText; } else { temp = beforeText + temp + afterText; } this.writeValue(temp); this.instance.setCursor({line: line + 1, ch: ch + text.length}); } else { temp = beforeText + temp + afterText; this.writeValue(temp); if (text.indexOf('\n') > -1) { this.instance.setCursor({line: line + 1, ch: ch + text.length}); } else { this.instance.setCursor({line: line, ch: ch + text.length}); } } this.instance.focus(); } public replace(text: string): void { const range = this.getSelectedRange(); const lines: any[] = this.getLines(); const beforeText: string = this.instance.doc.getRange({line: 0, ch: 0}, {line: range.from.line, ch: range.from.ch}) const afterText: string = this.instance.doc.getRange({line: range.to.line, ch: range.to.ch}, { line: lines.length, ch: 0 }) text = beforeText + text + afterText; this.writeValue(text); this.instance.setCursor({line: range.from.line, ch: range.from.ch}); this.instance.focus(); } private getSelectedRange() { return {from: this.instance.getCursor('start'), to: this.instance.getCursor('end')}; } public resize(height: number): void { this.instance.setSize('100%', height - 2); } public getSelection(): string { return this.instance.getSelection(); } public editorFocus(): void { this.instance.focus(); } public getEditor(): any { return this.instance; } public getFocusSelection(): string { // const lines = this.editor.session.getDocument().$lines; // const lines = this.instance.doc.children[0].lines; const lines: any[] = this.getLines(); const crow = this.instance.doc.getCursor().line let qend: number = -1; let qstart: number = -1; if (lines[crow].text.indexOf(';') > -1) { for (let i = crow - 1; i >= 0; i = i - 1) { if (lines[i].text.indexOf(';') > -1) { // ; 있으면 qstart = i; this.instance.doc.setSelection({ch: 0, line: qstart + 1}, {ch: 0, line: crow + 1}); break; } } // 없다면. if (qstart === -1) { this.instance.doc.setSelection({ch: 0, line: 0}, {ch: 0, line: crow + 1}); } } else { // 현재 행에 ; 가 없을 경우. // 뒤로 조회 for (let i = crow; i < lines.length; i = i + 1) { if (lines[i].text.indexOf(';') > -1) { // ; 있으면 qend = i; // 뒤로 조회 for (let j = crow; j >= 0; j = j - 1) { if (lines[j].text.indexOf(';') > -1) { // ; 있으면 qstart = j; break; } } // 없다면 if (qstart === -1) { qstart = 0; this.instance.doc.setSelection({ch: 0, line: qstart}, {ch: 0, line: qend + 1}); } else { this.instance.doc.setSelection({ch: 0, line: qstart + 1}, {ch: 0, line: qend + 1}); } break; } // 없다면. if (qend === -1) { // 뒤로 조회 let cnt = 0; for (let j = crow; j >= 0; j = j - 1) { if (lines[j].text.indexOf(';') > -1 && cnt === 0) { // ; 있으면 qend = j; } if (lines[j].text.indexOf(';') > -1 && cnt === 1) { qstart = j; break; } if (lines[j].text.indexOf(';') > -1) { cnt = cnt + 1; } } this.instance.doc.setSelection({ch: 0, line: qstart + 1}, {ch: 0, line: qend + 1}); } } } return ''; } private isSubquery(str, parenthesisLevel) { return parenthesisLevel - (str.replace(/\(/g, '').length - str.replace(/\)/g, '').length) } private split_sql(str, tab) { return str.replace(/\s{1,}/g, ' ') .replace(/ AND /ig, '~::~' + tab + tab + 'AND ') .replace(/ BETWEEN /ig, '~::~' + tab + 'BETWEEN ') .replace(/ CASE /ig, '~::~' + 'CASE ') .replace(/ ELSE /ig, '~::~' + 'ELSE ') .replace(/ END /ig, '~::~' + 'END ') .replace(/ FROM /ig, '~::~FROM ') .replace(/ GROUP\s{1,}BY/ig, '~::~GROUP BY ') .replace(/ HAVING /ig, '~::~HAVING ') // .replace(/ SET /ig," SET~::~") .replace(/ IN /ig, ' IN ') .replace(/ JOIN /ig, '~::~JOIN ') .replace(/ CROSS~::~{1,}JOIN /ig, '~::~CROSS JOIN ') .replace(/ INNER~::~{1,}JOIN /ig, '~::~INNER JOIN ') .replace(/ LEFT~::~{1,}JOIN /ig, '~::~LEFT JOIN ') .replace(/ RIGHT~::~{1,}JOIN /ig, '~::~RIGHT JOIN ') .replace(/ ON /ig, '~::~' + tab + 'ON ') .replace(/ OR /ig, '~::~' + tab + tab + 'OR ') .replace(/ ORDER\s{1,}BY/ig, '~::~ORDER BY ') .replace(/ OVER /ig, '~::~' + tab + 'OVER ') .replace(/\(\s{0,}SELECT /ig, '~::~(SELECT ') .replace(/\)\s{0,}SELECT /ig, ')~::~SELECT ') .replace(/ THEN /ig, ' ~::~' + 'THEN ') .replace(/ UNION /ig, '~::~UNION~::~') .replace(/ USING /ig, '~::~USING ') .replace(/ WHEN /ig, '~::~' + 'WHEN ') .replace(/ WHERE /ig, '~::~WHERE ') .replace(/ WITH /ig, '~::~WITH ') // .replace(/\,\s{0,}\(/ig,",~::~( ") // .replace(/\,/ig,",~::~"+tab+tab+ '') .replace(/ ALL /ig, ' ALL ') .replace(/ AS /ig, ' AS ') .replace(/ ASC /ig, ' ASC ') .replace(/ DESC /ig, ' DESC ') .replace(/ DISTINCT /ig, ' DISTINCT ') .replace(/ EXISTS /ig, ' EXISTS ') .replace(/ NOT /ig, ' NOT ') .replace(/ NULL /ig, ' NULL ') .replace(/ LIKE /ig, ' LIKE ') .replace(/\s{0,}SELECT /ig, 'SELECT ') .replace(/\s{0,}UPDATE /ig, 'UPDATE ') .replace(/ SET /ig, ' SET ') .replace(/\;/ig, '\;~::~') .replace(/~::~{1,}/g, '~::~') .split('~::~'); } private createShiftArr(step) { let space = ' '; if (isNaN(parseInt(step, 10))) { // argument is string space = step; } else { // argument is integer switch (step) { case 1: space = ' '; break; case 2: space = ' '; break; case 3: space = ' '; break; case 4: space = ' '; break; case 5: space = ' '; break; case 6: space = ' '; break; case 7: space = ' '; break; case 8: space = ' '; break; case 9: space = ' '; break; case 10: space = ' '; break; case 11: space = ' '; break; case 12: space = ' '; break; } } const shift = ['\n']; // array of shifts for (let ix = 0; ix < 100; ix++) { shift.push(shift[ix] + space); } return shift; } public formatter(text, step) { const that = this; const arByQuote = text.replace(/\s{1,}/g, ' ').replace(/\'/ig, '~::~\'').split('~::~'); let len = arByQuote.length; let ar = []; let deep = 0; const tab = step; // +this.step, let parenthesisLevel = 0; let str = ''; let ix = 0; const shift = step ? that.createShiftArr(step) : undefined; for (ix = 0; ix < len; ix++) { if (ix % 2) { ar = ar.concat(arByQuote[ix]); } else { ar = ar.concat(that.split_sql(arByQuote[ix], tab)); } } len = ar.length; for (ix = 0; ix < len; ix++) { parenthesisLevel = that.isSubquery(ar[ix], parenthesisLevel); if (/\s{0,}\s{0,}SELECT\s{0,}/.exec(ar[ix])) { ar[ix] = ar[ix].replace(/\,/g, ',\n' + tab + tab + '') } if (/\s{0,}\s{0,}SET\s{0,}/.exec(ar[ix])) { ar[ix] = ar[ix].replace(/\,/g, ',\n' + tab + tab + '') } if (/\s{0,}\(\s{0,}SELECT\s{0,}/.exec(ar[ix])) { deep++; str += shift[deep] + ar[ix]; } else if (/\'/.exec(ar[ix])) { if (parenthesisLevel < 1 && deep) { deep--; } str += ar[ix]; } else { str += shift[deep] + ar[ix]; if (parenthesisLevel < 1 && deep) { deep--; } } // const junk = 0; } str = str.replace(/^\n{1,}/, '').replace(/\n{1,}/g, '\n'); return str; } public setOptions(param) { this.instance.options.hintOptions = {tables: param}; } public setModeOptions(param) { this.instance.setOption('mode', param); this.instance.refresh(); } public getLines() { const lines: any[] = []; this.instance.doc.children.forEach((item) => { if (!isUndefined(item.lines)) { item.lines.forEach((item2, _idx) => { lines.push(item2); }); } else { this.getSubLines(item, lines); } }); return lines; } public getSubLines(item, lines) { item.children.forEach((item2) => { if (!isUndefined(item2.lines)) { item2.lines.forEach((item3) => { lines.push(item3); }); } else { this.getSubLines(item2, lines); } }) return lines; } }
the_stack
import { PoolClient } from "pg" import QueryStream from "pg-query-stream" import { boardReducer } from "../../common/src/board-reducer" import { Board, BoardAccessPolicy, BoardHistoryEntry, exampleBoard, Id, isBoardEmpty, Serial, } from "../../common/src/domain" import { migrateBoard, mkBootStrapEvent } from "../../common/src/migration" import { inTransaction, withDBClient } from "./db" import * as uuid from "uuid" export type BoardAndAccessTokens = { board: Board accessTokens: string[] } export type BoardInfo = { id: Id name: string ws_host: string | null } export async function getBoardInfo(id: Id): Promise<BoardInfo | null> { const result = await withDBClient((client) => client.query("SELECT id, name, ws_host FROM board WHERE id=$1", [id])) return result.rows.length === 1 ? (result.rows[0] as BoardInfo) : null } export async function fetchBoard(id: Id): Promise<BoardAndAccessTokens | null> { return await inTransaction(async (client) => { const result = await client.query("SELECT content FROM board WHERE id=$1", [id]) if (result.rows.length == 0) { return null } else { const snapshot = result.rows[0].content as Board let historyEventCount = 0 let lastSerial = 0 let board = snapshot function updateBoardWithEventChunk(chunk: BoardHistoryEntry[]) { board = chunk.reduce((b, e) => boardReducer(b, e)[0], board) historyEventCount += chunk.length lastSerial = chunk[chunk.length - 1].serial ?? snapshot.serial } await getBoardHistory(id, snapshot.serial, updateBoardWithEventChunk).catch((error) => { console.error(error.message) console.error(`Error fetching board history for snapshot update for board ${id}. Rebooting snapshot...`) board = { ...snapshot, items: {}, connections: [] } return getFullBoardHistory(id, client, updateBoardWithEventChunk) }) const serial = (historyEventCount > 0 ? lastSerial : snapshot.serial) || 0 console.log( `Loaded board ${id} at serial ${serial} from snapshot at serial ${snapshot.serial} and ${historyEventCount} events after snapshot`, ) if (historyEventCount > 1000 /* time to create a new snapshot*/) { console.log( `Saving snapshot for board ${id} at serial ${serial}/${snapshot.serial} with ${historyEventCount} new events`, ) await saveBoardSnapshot(mkSnapshot(board, serial), client) } const accessTokens = ( await client.query("SELECT token FROM board_api_token WHERE board_id=$1", [id]) ).rows.map((row) => row.token) return { board: { ...board, serial }, accessTokens } } }) } export async function createBoard(board: Board): Promise<void> { await inTransaction(async (client) => { const result = await client.query("SELECT id FROM board WHERE id=$1", [board.id]) if (result.rows.length > 0) throw Error("Board already exists: " + board.id) client.query(`INSERT INTO board(id, name, content) VALUES ($1, $2, $3)`, [ board.id, board.name, mkSnapshot(board, 0), ]) if (!isBoardEmpty(board)) { console.log(`Creating non-empty board ${board.id} -> bootstrapping history`) storeEventHistoryBundle(board.id, [mkBootStrapEvent(board.id, board)], client) } }) } export async function updateBoard({ boardId, name, accessPolicy, }: { boardId: Id name: string accessPolicy?: BoardAccessPolicy }) { await inTransaction(async (client) => { const result = await client.query("SELECT content FROM board WHERE id=$1", [boardId]) if (result.rows.length !== 1) throw Error("Board not found: " + boardId) let content = result.rows[0].content if (name) { content = { ...content, name } } else { name = content.name } if (accessPolicy) content = { ...content, accessPolicy } await client.query("UPDATE board SET content=$1, name=$2 WHERE id=$3", [content, name, boardId]) }) } export async function createAccessToken(board: Board): Promise<string> { const token = uuid.v4() await inTransaction(async (client) => client.query("INSERT INTO board_api_token (board_id, token) VALUES ($1, $2)", [board.id, token]), ) return token } export async function saveRecentEvents(id: Id, recentEvents: BoardHistoryEntry[]) { await inTransaction(async (client) => storeEventHistoryBundle(id, recentEvents, client)) } type StreamingBoardEventCallback = (chunk: BoardHistoryEntry[]) => void // Due to memory concerns we fetch board histories from DB as chunks, // which are currently implemented as sort of a poor-man's observable function streamingBoardEventsQuery(text: string, values: any[], client: PoolClient, cb: StreamingBoardEventCallback) { return new Promise((resolve, reject) => { const query = new QueryStream(text, values) const stream = client.query(query) stream.on("error", reject) stream.on("end", resolve) stream.on("data", (row) => { try { const chunk = row.events?.events as BoardHistoryEntry[] | undefined if (!chunk) { throw Error(`Unexpected DB row value ${chunk}`) } cb(chunk) } catch (error) { console.error(error) stream.destroy() reject(error) } }) }) } export function getFullBoardHistory(id: Id, client: PoolClient, cb: StreamingBoardEventCallback) { return streamingBoardEventsQuery( `SELECT events FROM board_event WHERE board_id=$1 ORDER BY last_serial`, [id], client, cb, ) } export async function getBoardHistory(id: Id, afterSerial: Serial, cb: StreamingBoardEventCallback): Promise<void> { await withDBClient(async (client) => { let firstSerial = -1 let lastSerial = -1 let firstValidSerial = -1 await streamingBoardEventsQuery( `SELECT events FROM board_event WHERE board_id=$1 AND last_serial >= $2 ORDER BY last_serial`, [id, afterSerial], client, (chunk) => { if (firstSerial === -1 && typeof chunk[0]?.serial === "number") { firstSerial = chunk[0]?.serial } lastSerial = chunk[chunk.length - 1].serial ?? -1 const validEventsAfter = chunk.filter((r) => r.serial! > afterSerial) if (validEventsAfter.length === 0) { // Got chunk where no events have serial greater than the snapshot point -- discard it return } if (firstValidSerial === -1 && typeof validEventsAfter[0].serial === "number") { firstValidSerial = validEventsAfter[0].serial } cb(validEventsAfter) return }, ) // Client is up to date, ok if (lastSerial === afterSerial) { return } // Found continuous history, ok if (firstValidSerial === afterSerial + 1) { return } if (firstValidSerial === -1) { if (afterSerial === 0) { // Requesting from start, zero events found, is ok return } // Client claims to be in the future, not ok throw Error( `Cannot find history to start after the requested serial ${afterSerial} for board ${id}. Seems like the requested serial is higher than currently stored in DB`, ) } // Found noncontinuous event timeline, not ok throw Error( `Cannot find history to start after the requested serial ${afterSerial} for board ${id}. Found history for ${firstValidSerial}..${lastSerial}`, ) }) } export function verifyContinuity(boardId: Id, init: Serial, ...histories: BoardHistoryEntry[][]) { for (let history of histories) { if (history.length > 0) { if (!verifyTwoPoints(boardId, init, history[0].serial!)) { return false } init = history[history.length - 1].serial! } } return true } function verifyTwoPoints(boardId: Id, a: Serial, b: Serial) { if (b !== a + 1) { console.error(`History discontinuity: ${a} -> ${b} for board ${boardId}`) return false } return true } export function mkSnapshot(board: Board, serial: Serial) { return migrateBoard({ ...board, serial }) } export async function saveBoardSnapshot(board: Board, client: PoolClient) { console.log(`Save board snapshot ${board.id} at serial ${board.serial}`) client.query(`UPDATE board set name=$2, content=$3 WHERE id=$1`, [board.id, board.name, board]) } export async function storeEventHistoryBundle( boardId: Id, events: BoardHistoryEntry[], client: PoolClient, savedAt = new Date(), ) { if (events.length > 0) { const firstSerial = events[0].serial! const lastSerial = events[events.length - 1].serial! await client.query( `INSERT INTO board_event(board_id, first_serial, last_serial, events, saved_at) VALUES ($1, $2, $3, $4, $5)`, [boardId, firstSerial, lastSerial, { events }, savedAt], ) } } export type BoardHistoryBundle = { board_id: Id last_serial: Serial events: { events: BoardHistoryEntry[] } } export async function getBoardHistoryBundles(client: PoolClient, id: Id): Promise<BoardHistoryBundle[]> { return ( await client.query( `SELECT board_id, last_serial, events FROM board_event WHERE board_id=$1 ORDER BY last_serial`, [id], ) ).rows } export async function getBoardHistoryBundlesWithLastSerialsBetween( client: PoolClient, id: Id, lsMin: Serial, lsMax: Serial, ): Promise<BoardHistoryBundle[]> { return ( await client.query( `SELECT board_id, last_serial, events FROM board_event WHERE board_id=$1 AND last_serial >= $2 AND last_serial <= $3 ORDER BY last_serial`, [id, lsMin, lsMax], ) ).rows } export type BoardHistoryBundleMeta = { board_id: Id first_serial: Serial last_serial: Serial saved_at: Date } export async function getBoardHistoryBundleMetas(client: PoolClient, id: Id): Promise<BoardHistoryBundleMeta[]> { return ( await client.query( `SELECT board_id, last_serial, first_serial, saved_at FROM board_event WHERE board_id=$1 ORDER BY last_serial`, [id], ) ).rows } export function verifyContinuityFromMetas(boardId: Id, init: Serial, bundles: BoardHistoryBundleMeta[]) { for (let bundle of bundles) { if (!verifyTwoPoints(boardId, init, bundle.first_serial)) { return false } init = bundle.last_serial } return true } export async function findAllBoards(client: PoolClient): Promise<Id[]> { const result = await client.query("SELECT id FROM board") return result.rows.map((row) => row.id) }
the_stack
import i18next from "i18next"; import { action, computed, runInAction } from "mobx"; import URI from "urijs"; import isDefined from "../../../Core/isDefined"; import loadJson from "../../../Core/loadJson"; import runLater from "../../../Core/runLater"; import TerriaError, { networkRequestError } from "../../../Core/TerriaError"; import AccessControlMixin from "../../../ModelMixins/AccessControlMixin"; import CatalogMemberMixin from "../../../ModelMixins/CatalogMemberMixin"; import GroupMixin from "../../../ModelMixins/GroupMixin"; import UrlMixin from "../../../ModelMixins/UrlMixin"; import ArcGisPortalCatalogGroupTraits from "../../../Traits/TraitsClasses/ArcGisPortalCatalogGroupTraits"; import ModelReference from "../../../Traits/ModelReference"; import { ArcGisItem, ArcGisPortalGroup, ArcGisPortalGroupSearchResponse, ArcGisPortalSearchResponse } from "./ArcGisPortalDefinitions"; import ArcGisPortalItemReference from "./ArcGisPortalItemReference"; import CatalogGroup from "../CatalogGroup"; import CommonStrata from "../../Definition/CommonStrata"; import CreateModel from "../../Definition/CreateModel"; import LoadableStratum from "../../Definition/LoadableStratum"; import { BaseModel } from "../../Definition/Model"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; import StratumOrder from "../../Definition/StratumOrder"; import Terria from "../../Terria"; export class ArcGisPortalStratum extends LoadableStratum( ArcGisPortalCatalogGroupTraits ) { static stratumName = "arcgisPortal"; groups: CatalogGroup[] = []; filteredGroups: CatalogGroup[] = []; datasets: ArcGisItem[] = []; filteredDatasets: ArcGisItem[] = []; constructor( readonly _catalogGroup: ArcGisPortalCatalogGroup, readonly _arcgisResponse: ArcGisPortalSearchResponse, readonly _arcgisGroupResponse: ArcGisPortalGroupSearchResponse | undefined ) { super(); this.datasets = this.getDatasets(); this.filteredDatasets = this.getFilteredDatasets(); this.groups = this.getGroups(); this.filteredGroups = this.getFilteredGroups(); } duplicateLoadableStratum(model: BaseModel): this { return new ArcGisPortalStratum( model as ArcGisPortalCatalogGroup, this._arcgisResponse, this._arcgisGroupResponse ) as this; } static async load( catalogGroup: ArcGisPortalCatalogGroup ): Promise<ArcGisPortalStratum | undefined> { var terria = catalogGroup.terria; let portalGroupsServerResponse: | ArcGisPortalGroupSearchResponse | undefined = undefined; let portalItemsServerResponse: | ArcGisPortalSearchResponse | undefined = undefined; // If we need to group by groups we use slightly different API's // that allow us to get the data more effectively if ( catalogGroup.groupBy === "organisationsGroups" || catalogGroup.groupBy === "usersGroups" ) { if (catalogGroup.groupBy === "organisationsGroups") { const groupSearchUri = new URI(catalogGroup.url) .segment("/sharing/rest/community/groups") .addQuery({ num: 100, f: "json" }); if (catalogGroup.groupSearchParams !== undefined) { const groupSearchParams = catalogGroup.groupSearchParams; Object.keys(groupSearchParams).forEach((key: string) => groupSearchUri.addQuery(key, groupSearchParams[key]) ); } portalGroupsServerResponse = await paginateThroughResults( groupSearchUri, catalogGroup ); if (portalGroupsServerResponse === undefined) return undefined; } else if (catalogGroup.groupBy === "usersGroups") { const groupSearchUri = new URI(catalogGroup.url) .segment(`/sharing/rest/community/self`) .addQuery({ f: "json" }); const response = await getPortalInformation( groupSearchUri, catalogGroup ); if (response === undefined) return undefined; portalGroupsServerResponse = { total: response.groups.length, results: response.groups, start: 0, num: 0, nextStart: 0 }; } if (portalGroupsServerResponse === undefined) return undefined; // Then for each group we've got access to we get the content for (let i = 0; i < portalGroupsServerResponse.results.length; ++i) { const group: ArcGisPortalGroup = portalGroupsServerResponse.results[i]; const groupItemSearchUri = new URI(catalogGroup.url) .segment(`/sharing/rest/content/groups/${group.id}/search`) .addQuery({ num: 100, f: "json" }); if (catalogGroup.searchParams) { const searchParams = catalogGroup.searchParams; Object.keys(searchParams).forEach((key: string) => groupItemSearchUri.addQuery(key, searchParams[key]) ); } const groupResponse: | ArcGisPortalSearchResponse | undefined = await paginateThroughResults( groupItemSearchUri, catalogGroup ); if (groupResponse === undefined) return undefined; groupResponse.results.forEach((item: ArcGisItem) => { item.groupId = group.id; }); if (i === 0) { portalItemsServerResponse = groupResponse; } else if ( portalItemsServerResponse !== undefined && groupResponse !== undefined ) { portalItemsServerResponse.results = portalItemsServerResponse.results.concat( groupResponse.results ); } } } else { // If we don't need to group by Portal Groups then we'll search using // the regular endpoint const itemSearchUri = new URI(catalogGroup.url) .segment("/sharing/rest/search") .addQuery({ num: 100, f: "json" }); if (catalogGroup.searchParams !== undefined) { const searchParams = catalogGroup.searchParams; const params = Object.keys(searchParams); params.forEach((key: string) => itemSearchUri.addQuery(key, searchParams[key]) ); } portalItemsServerResponse = await paginateThroughResults( itemSearchUri, catalogGroup ); if ( catalogGroup.groupBy === "portalCategories" && portalItemsServerResponse !== undefined ) { const categories = new Map(); portalItemsServerResponse.results.forEach(function(item) { item.categories.forEach(function(category: string, index: number) { if (index === 0) { item.groupId = category; } // "/Categories/Land Parcel and Property" if (!categories.has(category)) { const categoryPieces = category.split("/"); const categoryGroup = { id: category, title: categoryPieces[categoryPieces.length - 1] }; categories.set(category, categoryGroup); } }); }); portalGroupsServerResponse = { total: categories.size, results: Array.from(categories.values()), start: 0, num: 0, nextStart: 0 }; } } if (portalItemsServerResponse === undefined) return undefined; return new ArcGisPortalStratum( catalogGroup, portalItemsServerResponse, portalGroupsServerResponse ); } @computed get members(): ModelReference[] { if (this.filteredGroups.length > 0) { const groupIds: ModelReference[] = []; this.filteredGroups.forEach(g => { if (this._catalogGroup.hideEmptyGroups && g.members.length > 0) { groupIds.push(g.uniqueId as ModelReference); } else if (!this._catalogGroup.hideEmptyGroups) { groupIds.push(g.uniqueId as ModelReference); } }); return groupIds; } // Otherwise return the id's of all the resources of all the filtered datasets return this.filteredDatasets.map(ds => { return this._catalogGroup.uniqueId + "/" + ds.id; }, this); } private getDatasets(): ArcGisItem[] { return this._arcgisResponse.results; } private getFilteredDatasets(): ArcGisItem[] { if (this.datasets.length === 0) return []; if (this._catalogGroup.excludeMembers !== undefined) { const bl = this._catalogGroup.excludeMembers; return this.datasets.filter(ds => bl.indexOf(ds.title) === -1); } return this.datasets; } private getGroups(): CatalogGroup[] { if (this._catalogGroup.groupBy === "none") return []; let groups: CatalogGroup[] = [ ...createUngroupedGroup(this), ...createGroupsByPortalGroups(this) ]; groups.sort(function(a, b) { if (a.nameInCatalog === undefined || b.nameInCatalog === undefined) return 0; if (a.nameInCatalog < b.nameInCatalog) { return -1; } if (a.nameInCatalog > b.nameInCatalog) { return 1; } return 0; }); return groups; } private getFilteredGroups(): CatalogGroup[] { if (this.groups.length === 0) return []; if (this._catalogGroup.excludeMembers !== undefined) { const bl = this._catalogGroup.excludeMembers; return this.groups.filter(group => { if (group.name === undefined) return false; else return bl.indexOf(group.name) === -1; }); } return this.groups; } @action createMembersFromDatasets() { this.filteredDatasets.forEach(dataset => { this.createMemberFromDataset(dataset); }); } @action addCatalogItemToCatalogGroup( catalogItem: any, dataset: ArcGisItem, groupId: string ) { let group: | CatalogGroup | undefined = this._catalogGroup.terria.getModelById( CatalogGroup, groupId ); if (group !== undefined) { group.add(CommonStrata.definition, catalogItem); } } @action addCatalogItemByPortalGroupsToCatalogGroup( catalogItem: any, dataset: ArcGisItem ) { if (dataset.groupId === undefined) { const groupId = this._catalogGroup.uniqueId + "/ungrouped"; this.addCatalogItemToCatalogGroup(catalogItem, dataset, groupId); return; } const groupId = this._catalogGroup.uniqueId + "/" + dataset.groupId; this.addCatalogItemToCatalogGroup(catalogItem, dataset, groupId); } @action createMemberFromDataset(arcgisDataset: ArcGisItem) { if (!isDefined(arcgisDataset.id)) { return; } const id = this._catalogGroup.uniqueId; const itemId = `${id}/${arcgisDataset.id}`; let item = this._catalogGroup.terria.getModelById( ArcGisPortalItemReference, itemId ); if (item === undefined) { item = new ArcGisPortalItemReference(itemId, this._catalogGroup.terria); item.setDataset(arcgisDataset); item.setArcgisPortalCatalog(this._catalogGroup); item.setSupportedFormatFromItem(arcgisDataset); item.setArcgisStrata(item); item.terria.addModel(item); } if ( this._catalogGroup.groupBy === "organisationsGroups" || this._catalogGroup.groupBy === "usersGroups" || this._catalogGroup.groupBy === "portalCategories" ) { this.addCatalogItemByPortalGroupsToCatalogGroup(item, arcgisDataset); } if ( AccessControlMixin.isMixedInto(item) && arcgisDataset.access !== undefined ) { item.setAccessType(arcgisDataset.access); } } } StratumOrder.addLoadStratum(ArcGisPortalStratum.stratumName); export default class ArcGisPortalCatalogGroup extends UrlMixin( GroupMixin(CatalogMemberMixin(CreateModel(ArcGisPortalCatalogGroupTraits))) ) { static readonly type = "arcgis-portal-group"; get type() { return ArcGisPortalCatalogGroup.type; } get typeName() { return i18next.t("models.arcgisPortal.nameGroup"); } @computed get cacheDuration(): string { if (isDefined(super.cacheDuration)) { return super.cacheDuration; } return "0d"; } protected forceLoadMetadata(): Promise<void> { const portalStratum = <ArcGisPortalStratum | undefined>( this.strata.get(ArcGisPortalStratum.stratumName) ); if (!portalStratum) { return ArcGisPortalStratum.load(this).then(stratum => { if (stratum === undefined) return; runInAction(() => { this.strata.set(ArcGisPortalStratum.stratumName, stratum); }); }); } else { return Promise.resolve(); } } protected async forceLoadMembers() { const portalStratum = <ArcGisPortalStratum | undefined>( this.strata.get(ArcGisPortalStratum.stratumName) ); if (portalStratum) { await runLater(() => portalStratum.createMembersFromDatasets()); } } } function createGroup(groupId: string, terria: Terria, groupName: string) { const g = new CatalogGroup(groupId, terria); g.setTrait(CommonStrata.definition, "name", groupName); terria.addModel(g); return g; } function createUngroupedGroup(arcgisPortal: ArcGisPortalStratum) { const groupId = arcgisPortal._catalogGroup.uniqueId + "/ungrouped"; let existingGroup = arcgisPortal._catalogGroup.terria.getModelById( CatalogGroup, groupId ); if (existingGroup === undefined) { existingGroup = createGroup( groupId, arcgisPortal._catalogGroup.terria, arcgisPortal._catalogGroup.ungroupedTitle ); } return [existingGroup]; } function createGroupsByPortalGroups(arcgisPortal: ArcGisPortalStratum) { if (arcgisPortal._arcgisGroupResponse === undefined) return []; const out: CatalogGroup[] = []; arcgisPortal._arcgisGroupResponse.results.forEach( (group: ArcGisPortalGroup) => { const groupId = arcgisPortal._catalogGroup.uniqueId + "/" + group.id; let existingGroup = arcgisPortal._catalogGroup.terria.getModelById( CatalogGroup, groupId ); if (existingGroup === undefined) { existingGroup = createGroup( groupId, arcgisPortal._catalogGroup.terria, group.title ); if (group.description) { existingGroup.setTrait( CommonStrata.definition, "description", group.description ); } } if ( AccessControlMixin.isMixedInto(existingGroup) && group.access !== undefined ) { existingGroup.setAccessType(group.access); } out.push(existingGroup); } ); return out; } async function paginateThroughResults( uri: any, catalogGroup: ArcGisPortalCatalogGroup ) { const arcgisPortalResponse = await getPortalInformation(uri, catalogGroup); if (arcgisPortalResponse === undefined || !arcgisPortalResponse) { throw networkRequestError({ title: i18next.t("models.arcgisPortal.errorLoadingTitle"), message: i18next.t("models.arcgisPortal.errorLoadingMessage") }); } let nextStart: number = arcgisPortalResponse.nextStart; while (nextStart !== -1) { nextStart = await getMoreResults( uri, catalogGroup, arcgisPortalResponse, nextStart ); } return arcgisPortalResponse; } async function getPortalInformation( uri: any, catalogGroup: ArcGisPortalCatalogGroup ) { try { const response = await loadJson( proxyCatalogItemUrl( catalogGroup, uri.toString(), catalogGroup.cacheDuration ) ); return response; } catch (err) { console.log(err); return undefined; } } async function getMoreResults( uri: any, catalogGroup: ArcGisPortalCatalogGroup, baseResults: ArcGisPortalSearchResponse, nextResultStart: number ) { uri.setQuery("start", nextResultStart); try { const arcgisPortalResponse = await getPortalInformation(uri, catalogGroup); if (arcgisPortalResponse === undefined) { return -1; } baseResults.results = baseResults.results.concat( arcgisPortalResponse.results ); return arcgisPortalResponse.nextStart; } catch (err) { console.log(err); return -1; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ApiOperation } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ApiManagementClient } from "../apiManagementClient"; import { OperationContract, ApiOperationListByApiNextOptionalParams, ApiOperationListByApiOptionalParams, ApiOperationListByApiResponse, ApiOperationGetEntityTagOptionalParams, ApiOperationGetEntityTagResponse, ApiOperationGetOptionalParams, ApiOperationGetResponse, ApiOperationCreateOrUpdateOptionalParams, ApiOperationCreateOrUpdateResponse, OperationUpdateContract, ApiOperationUpdateOptionalParams, ApiOperationUpdateResponse, ApiOperationDeleteOptionalParams, ApiOperationListByApiNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ApiOperation operations. */ export class ApiOperationImpl implements ApiOperation { private readonly client: ApiManagementClient; /** * Initialize a new instance of the class ApiOperation class. * @param client Reference to the service client */ constructor(client: ApiManagementClient) { this.client = client; } /** * Lists a collection of the operations for the specified API. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param options The options parameters. */ public listByApi( resourceGroupName: string, serviceName: string, apiId: string, options?: ApiOperationListByApiOptionalParams ): PagedAsyncIterableIterator<OperationContract> { const iter = this.listByApiPagingAll( resourceGroupName, serviceName, apiId, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByApiPagingPage( resourceGroupName, serviceName, apiId, options ); } }; } private async *listByApiPagingPage( resourceGroupName: string, serviceName: string, apiId: string, options?: ApiOperationListByApiOptionalParams ): AsyncIterableIterator<OperationContract[]> { let result = await this._listByApi( resourceGroupName, serviceName, apiId, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByApiNext( resourceGroupName, serviceName, apiId, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByApiPagingAll( resourceGroupName: string, serviceName: string, apiId: string, options?: ApiOperationListByApiOptionalParams ): AsyncIterableIterator<OperationContract> { for await (const page of this.listByApiPagingPage( resourceGroupName, serviceName, apiId, options )) { yield* page; } } /** * Lists a collection of the operations for the specified API. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param options The options parameters. */ private _listByApi( resourceGroupName: string, serviceName: string, apiId: string, options?: ApiOperationListByApiOptionalParams ): Promise<ApiOperationListByApiResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, options }, listByApiOperationSpec ); } /** * Gets the entity state (Etag) version of the API operation specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param options The options parameters. */ getEntityTag( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, options?: ApiOperationGetEntityTagOptionalParams ): Promise<ApiOperationGetEntityTagResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, operationId, options }, getEntityTagOperationSpec ); } /** * Gets the details of the API Operation specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, options?: ApiOperationGetOptionalParams ): Promise<ApiOperationGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, operationId, options }, getOperationSpec ); } /** * Creates a new operation in the API or updates an existing one. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param parameters Create parameters. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, parameters: OperationContract, options?: ApiOperationCreateOrUpdateOptionalParams ): Promise<ApiOperationCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, operationId, parameters, options }, createOrUpdateOperationSpec ); } /** * Updates the details of the operation in the API specified by its identifier. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param parameters API Operation Update parameters. * @param options The options parameters. */ update( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, ifMatch: string, parameters: OperationUpdateContract, options?: ApiOperationUpdateOptionalParams ): Promise<ApiOperationUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, operationId, ifMatch, parameters, options }, updateOperationSpec ); } /** * Deletes the specified operation in the API. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param operationId Operation identifier within an API. Must be unique in the current API Management * service instance. * @param ifMatch ETag of the Entity. ETag should match the current entity state from the header * response of the GET request or it should be * for unconditional update. * @param options The options parameters. */ delete( resourceGroupName: string, serviceName: string, apiId: string, operationId: string, ifMatch: string, options?: ApiOperationDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, operationId, ifMatch, options }, deleteOperationSpec ); } /** * ListByApiNext * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param apiId API revision identifier. Must be unique in the current API Management service instance. * Non-current revision has ;rev=n as a suffix where n is the revision number. * @param nextLink The nextLink from the previous successful call to the ListByApi method. * @param options The options parameters. */ private _listByApiNext( resourceGroupName: string, serviceName: string, apiId: string, nextLink: string, options?: ApiOperationListByApiNextOptionalParams ): Promise<ApiOperationListByApiNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, apiId, nextLink, options }, listByApiNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByApiOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OperationCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.top, Parameters.skip, Parameters.tags, Parameters.apiVersion ], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId ], headerParameters: [Parameters.accept], serializer }; const getEntityTagOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.ApiOperationGetEntityTagHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OperationContract, headersMapper: Mappers.ApiOperationGetHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.OperationContract, headersMapper: Mappers.ApiOperationCreateOrUpdateHeaders }, 201: { bodyMapper: Mappers.OperationContract, headersMapper: Mappers.ApiOperationCreateOrUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.operationId ], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch ], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.OperationContract, headersMapper: Mappers.ApiOperationUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.operationId ], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch1 ], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.operationId ], headerParameters: [Parameters.accept, Parameters.ifMatch1], serializer }; const listByApiNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OperationCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [ Parameters.filter, Parameters.top, Parameters.skip, Parameters.tags, Parameters.apiVersion ], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId, Parameters.apiId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import { AmbiguityInfo } from "./AmbiguityInfo"; import { ATN } from "./ATN"; import { ATNConfigSet } from "./ATNConfigSet"; import { ATNSimulator } from "./ATNSimulator"; import { BitSet } from "../misc/BitSet"; import { ContextSensitivityInfo } from "./ContextSensitivityInfo"; import { DecisionInfo } from "./DecisionInfo"; import { DFA } from "../dfa/DFA"; import { DFAState } from "../dfa/DFAState"; import { ErrorInfo } from "./ErrorInfo"; import { NotNull, Override } from "../Decorators"; import { LookaheadEventInfo } from "./LookaheadEventInfo"; import { Parser } from "../Parser"; import { ParserATNSimulator } from "./ParserATNSimulator"; import { ParserRuleContext } from "../ParserRuleContext"; import { PredicateEvalInfo } from "./PredicateEvalInfo"; import { PredictionContextCache } from "./PredictionContextCache"; import { SemanticContext } from "./SemanticContext"; import { SimulatorState } from "./SimulatorState"; import { TokenStream } from "../TokenStream"; /** * @since 4.3 */ export class ProfilingATNSimulator extends ParserATNSimulator { protected decisions: DecisionInfo[]; protected numDecisions: number; protected _input: TokenStream | undefined; protected _startIndex: number = 0; protected _sllStopIndex: number = 0; protected _llStopIndex: number = 0; protected currentDecision: number = 0; protected currentState: SimulatorState | undefined; /** At the point of LL failover, we record how SLL would resolve the conflict so that * we can determine whether or not a decision / input pair is context-sensitive. * If LL gives a different result than SLL's predicted alternative, we have a * context sensitivity for sure. The converse is not necessarily true, however. * It's possible that after conflict resolution chooses minimum alternatives, * SLL could get the same answer as LL. Regardless of whether or not the result indicates * an ambiguity, it is not treated as a context sensitivity because LL prediction * was not required in order to produce a correct prediction for this decision and input sequence. * It may in fact still be a context sensitivity but we don't know by looking at the * minimum alternatives for the current input. */ protected conflictingAltResolvedBySLL: number = 0; constructor(parser: Parser) { super(parser.interpreter.atn, parser); this.optimize_ll1 = false; this.reportAmbiguities = true; this.numDecisions = this.atn.decisionToState.length; this.decisions = []; for (let i = 0; i < this.numDecisions; i++) { this.decisions.push(new DecisionInfo(i)); } } public adaptivePredict(/*@NotNull*/ input: TokenStream, decision: number, outerContext: ParserRuleContext | undefined): number; public adaptivePredict(/*@NotNull*/ input: TokenStream, decision: number, outerContext: ParserRuleContext | undefined, useContext: boolean): number; @Override public adaptivePredict( @NotNull input: TokenStream, decision: number, outerContext: ParserRuleContext | undefined, useContext?: boolean): number { if (useContext !== undefined) { return super.adaptivePredict(input, decision, outerContext, useContext); } try { this._input = input; this._startIndex = input.index; // it's possible for SLL to reach a conflict state without consuming any input this._sllStopIndex = this._startIndex - 1; this._llStopIndex = -1; this.currentDecision = decision; this.currentState = undefined; this.conflictingAltResolvedBySLL = ATN.INVALID_ALT_NUMBER; let start: number[] = process.hrtime(); let alt: number = super.adaptivePredict(input, decision, outerContext); let stop: number[] = process.hrtime(); let nanoseconds: number = (stop[0] - start[0]) * 1000000000; if (nanoseconds === 0) { nanoseconds = stop[1] - start[1]; } else { // Add nanoseconds from start to end of that second, plus start of the end second to end nanoseconds += (1000000000 - start[1]) + stop[1]; } this.decisions[decision].timeInPrediction += nanoseconds; this.decisions[decision].invocations++; let SLL_k: number = this._sllStopIndex - this._startIndex + 1; this.decisions[decision].SLL_TotalLook += SLL_k; this.decisions[decision].SLL_MinLook = this.decisions[decision].SLL_MinLook === 0 ? SLL_k : Math.min(this.decisions[decision].SLL_MinLook, SLL_k); if (SLL_k > this.decisions[decision].SLL_MaxLook) { this.decisions[decision].SLL_MaxLook = SLL_k; this.decisions[decision].SLL_MaxLookEvent = new LookaheadEventInfo(decision, undefined, alt, input, this._startIndex, this._sllStopIndex, false); } if (this._llStopIndex >= 0) { let LL_k: number = this._llStopIndex - this._startIndex + 1; this.decisions[decision].LL_TotalLook += LL_k; this.decisions[decision].LL_MinLook = this.decisions[decision].LL_MinLook === 0 ? LL_k : Math.min(this.decisions[decision].LL_MinLook, LL_k); if (LL_k > this.decisions[decision].LL_MaxLook) { this.decisions[decision].LL_MaxLook = LL_k; this.decisions[decision].LL_MaxLookEvent = new LookaheadEventInfo(decision, undefined, alt, input, this._startIndex, this._llStopIndex, true); } } return alt; } finally { this._input = undefined; this.currentDecision = -1; } } @Override protected getStartState(dfa: DFA, input: TokenStream, outerContext: ParserRuleContext, useContext: boolean): SimulatorState | undefined { let state: SimulatorState | undefined = super.getStartState(dfa, input, outerContext, useContext); this.currentState = state; return state; } @Override protected computeStartState(dfa: DFA, globalContext: ParserRuleContext, useContext: boolean): SimulatorState { let state: SimulatorState = super.computeStartState(dfa, globalContext, useContext); this.currentState = state; return state; } @Override protected computeReachSet(dfa: DFA, previous: SimulatorState, t: number, contextCache: PredictionContextCache): SimulatorState | undefined { if (this._input === undefined) { throw new Error("Invalid state"); } let reachState: SimulatorState | undefined = super.computeReachSet(dfa, previous, t, contextCache); if (reachState == null) { // no reach on current lookahead symbol. ERROR. this.decisions[this.currentDecision].errors.push( new ErrorInfo(this.currentDecision, previous, this._input, this._startIndex, this._input.index), ); } this.currentState = reachState; return reachState; } @Override protected getExistingTargetState(previousD: DFAState, t: number): DFAState | undefined { if (this.currentState === undefined || this._input === undefined) { throw new Error("Invalid state"); } // this method is called after each time the input position advances if (this.currentState.useContext) { this._llStopIndex = this._input.index; } else { this._sllStopIndex = this._input.index; } let existingTargetState: DFAState | undefined = super.getExistingTargetState(previousD, t); if (existingTargetState != null) { // this method is directly called by execDFA; must construct a SimulatorState // to represent the current state for this case this.currentState = new SimulatorState(this.currentState.outerContext, existingTargetState, this.currentState.useContext, this.currentState.remainingOuterContext); if (this.currentState.useContext) { this.decisions[this.currentDecision].LL_DFATransitions++; } else { this.decisions[this.currentDecision].SLL_DFATransitions++; // count only if we transition over a DFA state } if (existingTargetState === ATNSimulator.ERROR) { let state: SimulatorState = new SimulatorState(this.currentState.outerContext, previousD, this.currentState.useContext, this.currentState.remainingOuterContext); this.decisions[this.currentDecision].errors.push( new ErrorInfo(this.currentDecision, state, this._input, this._startIndex, this._input.index), ); } } return existingTargetState; } @Override protected computeTargetState(dfa: DFA, s: DFAState, remainingGlobalContext: ParserRuleContext, t: number, useContext: boolean, contextCache: PredictionContextCache): [DFAState, ParserRuleContext | undefined] { let targetState: [DFAState, ParserRuleContext | undefined] = super.computeTargetState(dfa, s, remainingGlobalContext, t, useContext, contextCache); if (useContext) { this.decisions[this.currentDecision].LL_ATNTransitions++; } else { this.decisions[this.currentDecision].SLL_ATNTransitions++; } return targetState; } @Override protected evalSemanticContextImpl(pred: SemanticContext, parserCallStack: ParserRuleContext, alt: number): boolean { if (this.currentState === undefined || this._input === undefined) { throw new Error("Invalid state"); } let result: boolean = super.evalSemanticContextImpl(pred, parserCallStack, alt); if (!(pred instanceof SemanticContext.PrecedencePredicate)) { let fullContext: boolean = this._llStopIndex >= 0; let stopIndex: number = fullContext ? this._llStopIndex : this._sllStopIndex; this.decisions[this.currentDecision].predicateEvals.push( new PredicateEvalInfo(this.currentState, this.currentDecision, this._input, this._startIndex, stopIndex, pred, result, alt), ); } return result; } @Override protected reportContextSensitivity(dfa: DFA, prediction: number, acceptState: SimulatorState, startIndex: number, stopIndex: number): void { if (this._input === undefined) { throw new Error("Invalid state"); } if (prediction !== this.conflictingAltResolvedBySLL) { this.decisions[this.currentDecision].contextSensitivities.push( new ContextSensitivityInfo(this.currentDecision, acceptState, this._input, startIndex, stopIndex), ); } super.reportContextSensitivity(dfa, prediction, acceptState, startIndex, stopIndex); } @Override protected reportAttemptingFullContext(dfa: DFA, conflictingAlts: BitSet, conflictState: SimulatorState, startIndex: number, stopIndex: number): void { if (conflictingAlts != null) { this.conflictingAltResolvedBySLL = conflictingAlts.nextSetBit(0); } else { this.conflictingAltResolvedBySLL = conflictState.s0.configs.getRepresentedAlternatives().nextSetBit(0); } this.decisions[this.currentDecision].LL_Fallback++; super.reportAttemptingFullContext(dfa, conflictingAlts, conflictState, startIndex, stopIndex); } @Override protected reportAmbiguity(@NotNull dfa: DFA, D: DFAState, startIndex: number, stopIndex: number, exact: boolean, @NotNull ambigAlts: BitSet, @NotNull configs: ATNConfigSet): void { if (this.currentState === undefined || this._input === undefined) { throw new Error("Invalid state"); } let prediction: number; if (ambigAlts != null) { prediction = ambigAlts.nextSetBit(0); } else { prediction = configs.getRepresentedAlternatives().nextSetBit(0); } if (this.conflictingAltResolvedBySLL !== ATN.INVALID_ALT_NUMBER && prediction !== this.conflictingAltResolvedBySLL) { // Even though this is an ambiguity we are reporting, we can // still detect some context sensitivities. Both SLL and LL // are showing a conflict, hence an ambiguity, but if they resolve // to different minimum alternatives we have also identified a // context sensitivity. this.decisions[this.currentDecision].contextSensitivities.push( new ContextSensitivityInfo(this.currentDecision, this.currentState, this._input, startIndex, stopIndex), ); } this.decisions[this.currentDecision].ambiguities.push( new AmbiguityInfo(this.currentDecision, this.currentState, ambigAlts, this._input, startIndex, stopIndex), ); super.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs); } // --------------------------------------------------------------------- public getDecisionInfo(): DecisionInfo[] { return this.decisions; } public getCurrentState(): SimulatorState | undefined { return this.currentState; } }
the_stack
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. import * as child_process from "child_process"; import * as fs from "fs"; import * as path from "path"; import { URL } from "url"; import * as semver from "semver"; import * as os from "os"; import * as nls from "vscode-nls"; nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(); const localize = nls.loadMessageBundle(); export interface IPluginDetails { PluginId: string; PluginType: string; Version: string; } export class ProjectType { constructor( public isMeteor: boolean, public isMobilefirst: boolean, public isPhonegap: boolean, public isCordova: boolean, public ionicMajorVersion?: number ) {} get isIonic(): boolean { return !!this.ionicMajorVersion; } } export class CordovaProjectHelper { private static PROJECT_TYPINGS_FOLDERNAME = "typings"; private static PROJECT_TYPINGS_PLUGINS_FOLDERNAME = "plugins"; private static PROJECT_TYPINGS_CORDOVA_FOLDERNAME = "cordova"; private static PROJECT_TYPINGS_CORDOVA_IONIC_FOLDERNAME = "cordova-ionic"; private static VSCODE_DIR: string = ".vscode"; private static PLATFORMS_PATH: string = "platforms"; private static PLUGINS_FETCH_FILENAME: string = "fetch.json"; private static CONFIG_XML_FILENAME: string = "config.xml"; private static PROJECT_PLUGINS_DIR: string = "plugins"; private static IONIC_PROJECT_FILE: string = "ionic.project"; private static CONFIG_IONIC_FILENAME: string = "ionic.config.json"; private static IONIC_LIB_DEFAULT_PATH: string = path.join("www", "lib", "ionic"); private static CORE_PLUGIN_LIST: string[] = ["cordova-plugin-battery-status", "cordova-plugin-camera", "cordova-plugin-console", "cordova-plugin-contacts", "cordova-plugin-device", "cordova-plugin-device-motion", "cordova-plugin-device-orientation", "cordova-plugin-dialogs", "cordova-plugin-file", "cordova-plugin-file-transfer", "cordova-plugin-geolocation", "cordova-plugin-globalization", "cordova-plugin-inappbrowser", "cordova-plugin-media", "cordova-plugin-media-capture", "cordova-plugin-network-information", "cordova-plugin-splashscreen", "cordova-plugin-statusbar", "cordova-plugin-vibration", "cordova-plugin-ms-azure-mobile-apps", "cordova-plugin-hockeyapp", "cordova-plugin-code-push", "cordova-plugin-bluetoothle", "phonegap-plugin-push", "cordova-plugin-ms-azure-mobile-engagement", "cordova-plugin-whitelist", "cordova-plugin-crosswalk-webview", "cordova-plugin-ms-adal", "com-intel-security-cordova-plugin", "cordova-sqlite-storage", "cordova-plugin-ms-intune-mam"]; /** * Helper function check if a file exists. */ public static existsSync(path: string): boolean { try { // Attempt to get the file stats fs.statSync(path); return true; } catch (error) { return false; } } /** * Helper (asynchronous) function to check if a file or directory exists */ public static exists(filename: string): Promise<boolean> { return fs.promises.stat(filename) .then(() => { return true; }) .catch(() => { return false; }); } /** * Helper (synchronous) function to create a directory recursively */ public static makeDirectoryRecursive(dirPath: string): void { let parentPath = path.dirname(dirPath); if (!CordovaProjectHelper.existsSync(parentPath)) { CordovaProjectHelper.makeDirectoryRecursive(parentPath); } fs.mkdirSync(dirPath); } /** * Helper (synchronous) function to delete a directory recursively */ public static deleteDirectoryRecursive(dirPath: string): void { if (fs.existsSync(dirPath)) { if (fs.lstatSync(dirPath).isDirectory()) { fs.readdirSync(dirPath).forEach(function (file) { let curPath = path.join(dirPath, file); CordovaProjectHelper.deleteDirectoryRecursive(curPath); }); fs.rmdirSync(dirPath); } else { fs.unlinkSync(dirPath); } } } /** * Helper function to asynchronously copy a file */ public static copyFile(from: string, to: string): Promise<void> { return fs.promises.copyFile(from, to); } /** * Helper function to get the list of plugins installed for the project. */ public static getInstalledPlugins(projectRoot: string): string[] { let fetchJsonPath: string = path.resolve(projectRoot, CordovaProjectHelper.PROJECT_PLUGINS_DIR, CordovaProjectHelper.PLUGINS_FETCH_FILENAME); if (!CordovaProjectHelper.existsSync(fetchJsonPath)) { return []; } try { let fetchJsonContents = fs.readFileSync(fetchJsonPath, "utf8"); let fetchJson = JSON.parse(fetchJsonContents); return Object.keys(fetchJson); } catch (error) { console.error(error); return []; } } /** * Helper function to get the list of platforms installed for the project. */ public static getInstalledPlatforms(projectRoot: string): string[] { let platformsPath: string = path.resolve(projectRoot, CordovaProjectHelper.PLATFORMS_PATH); if (!CordovaProjectHelper.existsSync(platformsPath)) { return []; } try { let platformsDirContents = fs.readdirSync(platformsPath); return platformsDirContents.filter((platform) => { return platform.charAt(0) !== "."; }); } catch (error) { console.error(error); return []; } } public static getInstalledPluginDetails(projectRoot: string, pluginId: string): IPluginDetails { let packageJsonPath: string = path.resolve(projectRoot, CordovaProjectHelper.PROJECT_PLUGINS_DIR, pluginId, "package.json"); if (!CordovaProjectHelper.existsSync(packageJsonPath)) { return null; } try { let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")); let details: IPluginDetails = { PluginId: packageJson.name, Version: packageJson.version, PluginType: CordovaProjectHelper.CORE_PLUGIN_LIST.indexOf(pluginId) >= 0 ? "Core" : "Npm", }; return details; } catch (error) { console.error(error); return null; } } /** * Helper to check whether a workspace root equals to a Cordova project root */ public static isCordovaProject(workspaceRoot: string): boolean { return !!(CordovaProjectHelper.existsSync(path.join(workspaceRoot, CordovaProjectHelper.CONFIG_XML_FILENAME)) || CordovaProjectHelper.existsSync(path.join(workspaceRoot, CordovaProjectHelper.CONFIG_IONIC_FILENAME)) ); } public static checkPathBelongsToHierarchy(parentPath: string, childPath: string): boolean { let parentStepPath: string; let childStepPath: string = childPath; while (childStepPath !== parentPath) { parentStepPath = path.resolve(childStepPath, ".."); if (parentStepPath !== childStepPath) { childStepPath = parentStepPath; } else { // we have reached the filesystem root return false; } } return true; } /** * Helper function to get the target path for the type definition files (to be used for Cordova plugin intellisense). * Creates the target path if it does not exist already. */ public static getOrCreateTypingsTargetPath(projectRoot: string): string { if (projectRoot) { let targetPath = path.resolve(projectRoot, CordovaProjectHelper.VSCODE_DIR, CordovaProjectHelper.PROJECT_TYPINGS_FOLDERNAME); if (!CordovaProjectHelper.existsSync(targetPath)) { CordovaProjectHelper.makeDirectoryRecursive(targetPath); } return targetPath; } return null; } /** * Helper function to get the path to Cordova plugin type definitions folder */ public static getCordovaPluginTypeDefsPath(projectRoot: string): string { return path.resolve(CordovaProjectHelper.getOrCreateTypingsTargetPath(projectRoot), CordovaProjectHelper.PROJECT_TYPINGS_CORDOVA_FOLDERNAME, CordovaProjectHelper.PROJECT_TYPINGS_PLUGINS_FOLDERNAME); } /** * Helper function to get the path to Ionic plugin type definitions folder */ public static getIonicPluginTypeDefsPath(projectRoot: string): string { return path.resolve(CordovaProjectHelper.getOrCreateTypingsTargetPath(projectRoot), CordovaProjectHelper.PROJECT_TYPINGS_CORDOVA_IONIC_FOLDERNAME, CordovaProjectHelper.PROJECT_TYPINGS_PLUGINS_FOLDERNAME); } /** * Helper function to determine whether the project is an Ionic Angular project or not */ public static isIonicAngularProject(projectRoot: string): boolean { return !!this.determineIonicMajorVersion(projectRoot); } /** * Helper function to determine which version of Ionic the project belongs to */ public static determineIonicMajorVersion(projectRoot: string): number | undefined { // Ionic 1 check // First look for "ionic.project" at the project root if (fs.existsSync(path.join(projectRoot, CordovaProjectHelper.IONIC_PROJECT_FILE))) { return 1; // If not found, fall back to looking for "www/lib/ionic" folder. This isn't a 100% guarantee though: an Ionic project doesn't necessarily have an "ionic.project" and could have the Ionic lib // files in a non-default location } else if (fs.existsSync(path.join(projectRoot, CordovaProjectHelper.IONIC_LIB_DEFAULT_PATH))) { return 1; } const packageJsonPath = path.join(projectRoot, "package.json"); if (!fs.existsSync(packageJsonPath)) { return; } const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")); const dependencies = packageJson.dependencies || {}; const devDependencies = packageJson.devDependencies || {}; // Ionic 2 & 3 check const highestNotSupportedIonic2BetaVersion = "2.0.0-beta.9"; const highestNotSupportedIonic3BetaVersion = "3.0.0-beta.3"; if ((dependencies["ionic-angular"]) && (devDependencies["@ionic/app-scripts"] || dependencies["@ionic/app-scripts"])) { const ionicVersion = dependencies["ionic-angular"]; // If it's a valid version let's check it's greater than highest not supported Ionic major version beta if (semver.valid(ionicVersion)) { if (CordovaProjectHelper.versionSatisfiesInterval( ionicVersion, highestNotSupportedIonic2BetaVersion, "3.0.0") ) { return 2; } if (semver.gt(ionicVersion, highestNotSupportedIonic3BetaVersion)) { return 3; } } // If it's a valid range we check that the entire range is greater than highest not supported Ionic major version beta if (semver.validRange(ionicVersion)) { if (CordovaProjectHelper.versionRangeSatisfiesInterval( ionicVersion, highestNotSupportedIonic2BetaVersion, "3.0.0") ) { return 2; } if (semver.ltr(highestNotSupportedIonic3BetaVersion, ionicVersion)) { return 3; } } // Assuming for now that latest version is 3 if (ionicVersion === "latest" || ionicVersion === "nightly") { return 3; } } // Ionic 4, 5, 6 check const highestNotSupportedIonic4BetaVersion = "4.0.0-beta.19"; const highestNotSupportedIonic5BetaVersion = "5.0.0-beta.6"; const highestNotSupportedIonic6BetaVersion = "6.0.0-beta.7"; if (dependencies["@ionic/angular"]) { const ionicVersion = dependencies["@ionic/angular"]; // If it's a valid version let's check it's greater than highest not supported Ionic major version beta if (semver.valid(ionicVersion)) { if (CordovaProjectHelper.versionSatisfiesInterval( ionicVersion, highestNotSupportedIonic4BetaVersion, "5.0.0") ) { return 4; } if (CordovaProjectHelper.versionSatisfiesInterval( ionicVersion, highestNotSupportedIonic5BetaVersion, "6.0.0") ) { return 5; } if (semver.gt(ionicVersion, highestNotSupportedIonic6BetaVersion)) { return 6; } } // If it's a valid range we check that the entire range is greater than highest not supported Ionic major version beta if (semver.validRange(ionicVersion)) { if (CordovaProjectHelper.versionRangeSatisfiesInterval( ionicVersion, highestNotSupportedIonic4BetaVersion, "5.0.0") ) { return 4; } if (CordovaProjectHelper.versionRangeSatisfiesInterval( ionicVersion, highestNotSupportedIonic5BetaVersion, "6.0.0") ) { return 5; } if (semver.ltr(highestNotSupportedIonic6BetaVersion, ionicVersion)) { return 6; } } // Assuming for now that latest version is 6 if (ionicVersion === "latest" || ionicVersion === "nightly") { return 6; } } } /** * Helper function to determine whether the project has a tsconfig.json * manifest and can be considered as a typescript project. */ public static isTypescriptProject(projectRoot: string): boolean { return fs.existsSync(path.resolve(projectRoot, "tsconfig.json")); } public static getCliCommand(fsPath: string): string { const cliName = CordovaProjectHelper.isIonicAngularProject(fsPath) ? "ionic" : "cordova"; const commandExtension = os.platform() === "win32" ? ".cmd" : ""; const command = cliName + commandExtension; return command; } public static getIonicCliVersion(fsPath: string, command: string = CordovaProjectHelper.getCliCommand(fsPath)): string { const ionicInfo = child_process.spawnSync(command, ["-v", "--quiet"], { cwd: fsPath, env: { ...process.env, CI: "Hack to disable Ionic autoupdate prompt", }, }); let parseVersion = /\d+\.\d+\.\d+/.exec(ionicInfo.stdout.toString()); return parseVersion[0].trim(); } /** * Checks if ionic cli version is being used greater than specified version using semver. * @param fsPath directory to use for running command * @param version version to compare * @param command multiplatform command to use */ public static isIonicCliVersionGte(fsPath: string, version: string, command: string = CordovaProjectHelper.getCliCommand(fsPath)): boolean { try { const ionicVersion = CordovaProjectHelper.getIonicCliVersion(fsPath, command); return semver.gte(ionicVersion, version); } catch (err) { console.error(localize("ErrorWhileDetectingIonicCLIVersion", "Error while detecting Ionic CLI version"), err); } return true; } public static isIonicCliVersionGte3(fsPath: string, command: string = CordovaProjectHelper.getCliCommand(fsPath)): boolean { return CordovaProjectHelper.isIonicCliVersionGte(fsPath, "3.0.0", command); } public static getEnvArgument(launchArgs): any { let args = { ...launchArgs }; let env = process.env; if (args.envFile) { let buffer = fs.readFileSync(args.envFile, "utf8"); // Strip BOM if (buffer && buffer[0] === "\uFEFF") { buffer = buffer.substr(1); } buffer.split("\n").forEach((line: string) => { const r = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/); if (r !== null) { const key = r[1]; if (!env[key]) { // .env variables never overwrite existing variables let value = r[2] || ""; if (value.length > 0 && value.charAt(0) === "\"" && value.charAt(value.length - 1) === "\"") { value = value.replace(/\\n/gm, "\n"); } env[key] = value.replace(/(^['"]|['"]$)/g, ""); } } }); } if (args.env) { // launch config env vars overwrite .env vars for (let key in args.env) { if (args.env.hasOwnProperty(key)) { env[key] = args.env[key]; } } } return env; } public static properJoin(...segments: string[]): string { if (path.posix.isAbsolute(segments[0])) { return path.posix.join(...segments); } else if (path.win32.isAbsolute(segments[0])) { return path.win32.join(...segments); } else { return path.join(...segments); } } public static getPortFromURL(url: string): number { const serveURLInst = new URL(url); return +serveURLInst.port; } private static versionSatisfiesInterval( version: string, lowVersionEdge: string, highVersionEdge: string, ): boolean { return semver.gt(version, lowVersionEdge) && semver.lt(version, highVersionEdge); } private static versionRangeSatisfiesInterval( version: string, lowVersionEdge: string, highVersionEdge: string, ): boolean { return semver.ltr(lowVersionEdge, version) && semver.gtr(highVersionEdge, version); } }
the_stack
import { token, CdsTheme } from './token-utils'; const layout = { space: { xxs: token(2), xs: token(4), sm: token(6), md: token(12), lg: token(24), xl: token(48), xxl: token(96), }, grid: { cols: token(12, { static: true }), }, width: { xs: token('576px', { static: true }), sm: token('768px', { static: true }), md: token('992px', { static: true }), lg: token('1200px', { static: true }), xl: token('1440px', { static: true }), }, }; const space = { 0: token(0), 1: token(1), 2: token(2), 3: token(4), 4: token(6), 5: token(8), 6: token(12), 7: token(16), 8: token(18), 9: token(24), 10: token(32), 11: token(36), 12: token(48), 13: token(72), }; const color = { black: token([0, 0, 0]), white: token([0, 0, 100]), green: { 50: token([93, 80, 94]), 100: token([93, 80, 83]), 200: token([93, 80, 70]), 300: token([93, 80, 56]), 400: token([93, 80, 48]), 500: token([93, 80, 44]), 600: token([93, 80, 37]), 700: token([93, 80, 28]), 800: token([93, 80, 23]), 900: token([93, 80, 17]), 1000: token([93, 80, 12]), }, blue: { 50: token([198, 100, 95]), 100: token([198, 100, 87]), 200: token([198, 100, 78]), 300: token([198, 100, 70]), 400: token([198, 100, 59]), 500: token([198, 100, 48]), 600: token([198, 100, 43]), 700: token([198, 100, 34]), 800: token([198, 100, 27]), 900: token([198, 100, 21]), 1000: token([198, 100, 15]), }, violet: { 50: token([282, 100, 97]), 100: token([282, 80, 91]), 200: token([282, 73, 83]), 300: token([282, 66, 74]), 400: token([282, 60, 65]), 500: token([282, 60, 57]), 600: token([282, 60, 49]), 700: token([283, 80, 36]), 800: token([282, 100, 26]), 900: token([282, 100, 19]), 1000: token([282, 100, 14]), }, red: { 50: token([9, 100, 97]), 100: token([9, 100, 94]), 200: token([9, 100, 88]), 300: token([9, 100, 79]), 400: token([9, 100, 71]), 500: token([9, 100, 65]), 600: token([9, 100, 60]), 700: token([9, 100, 44]), 800: token([9, 100, 38]), 900: token([9, 100, 28]), 1000: token([9, 100, 22]), }, ochre: { 50: token([41, 100, 96]), 100: token([41, 100, 92]), 200: token([41, 100, 86]), 300: token([41, 100, 78]), 400: token([41, 100, 70]), 500: token([40, 100, 59]), 600: token([39, 100, 50]), 700: token([38, 100, 42]), 800: token([37, 100, 32]), 900: token([36, 100, 27]), 1000: token([35, 100, 19]), }, lavender: { 50: token([238, 100, 96]), 100: token([238, 58, 88]), 200: token([238, 53, 79]), 300: token([238, 52, 70]), 400: token([238, 58, 64]), 500: token([238, 59, 58]), 600: token([238, 60, 52]), 700: token([238, 69, 45]), 800: token([238, 100, 32]), 900: token([238, 100, 22]), 1000: token([238, 100, 14]), }, azure: { 50: token([211, 100, 95]), 100: token([211, 100, 88]), 200: token([211, 100, 81]), 300: token([211, 100, 70]), 400: token([211, 100, 62]), 500: token([211, 100, 54]), 600: token([211, 100, 46]), 700: token([211, 100, 37]), 800: token([211, 100, 26]), 900: token([211, 100, 18]), 1000: token([211, 100, 14]), }, aqua: { 50: token([184, 100, 96]), 100: token([184, 100, 86]), 200: token([184, 100, 75]), 300: token([184, 100, 62]), 400: token([184, 100, 48]), 500: token([184, 100, 43]), 600: token([184, 100, 34]), 700: token([184, 100, 25]), 800: token([184, 100, 18]), 900: token([184, 100, 13]), 1000: token([184, 100, 10]), }, jade: { 50: token([160, 83, 95]), 100: token([160, 82, 88]), 200: token([160, 78, 78]), 300: token([160, 69, 65]), 400: token([160, 69, 53]), 500: token([160, 64, 45]), 600: token([160, 69, 36]), 700: token([160, 64, 30]), 800: token([160, 100, 21]), 900: token([160, 70, 21]), 1000: token([160, 69, 19]), }, yellow: { 50: token([50, 100, 95]), 100: token([50, 100, 84]), 200: token([50, 100, 73]), 300: token([50, 100, 57]), 400: token([46, 100, 52]), 500: token([44, 100, 47]), 600: token([42, 100, 42]), 700: token([40, 100, 35]), 800: token([40, 100, 26]), 900: token([40, 100, 18]), 1000: token([40, 100, 13]), }, tangerine: { 50: token([25, 100, 95]), 100: token([25, 100, 88]), 200: token([25, 94, 78]), 300: token([25, 100, 72]), 400: token([25, 100, 62]), 500: token([25, 100, 48]), 600: token([25, 100, 41]), 700: token([25, 100, 34]), 800: token([25, 100, 25]), 900: token([25, 100, 19]), 1000: token([25, 100, 15]), }, magenta: { 50: token([345, 100, 95]), 100: token([345, 100, 87]), 200: token([345, 100, 79]), 300: token([345, 100, 70]), 400: token([345, 100, 61]), 500: token([345, 81, 50]), 600: token([345, 83, 40]), 700: token([345, 91, 31]), 800: token([345, 100, 24]), 900: token([345, 100, 19]), 1000: token([345, 100, 15]), }, pink: { 50: token([324, 100, 97]), 100: token([324, 95, 91]), 200: token([324, 84, 81]), 300: token([324, 78, 70]), 400: token([324, 78, 62]), 500: token([324, 64, 51]), 600: token([324, 80, 39]), 700: token([324, 100, 30]), 800: token([324, 100, 24]), 900: token([324, 100, 18]), 1000: token([324, 100, 15]), }, warmGray: { 50: token([282, 3, 97]), 100: token([282, 3, 92]), 200: token([282, 3, 84]), 300: token([282, 3, 74]), 400: token([282, 3, 63]), 500: token([282, 3, 54]), 600: token([282, 3, 43]), 700: token([282, 3, 35]), 800: token([282, 3, 28]), 900: token([282, 3, 20]), 1000: token([282, 3, 14]), }, slate: { 50: token([238, 20, 96]), 100: token([238, 20, 91]), 200: token([238, 20, 82]), 300: token([238, 20, 73]), 400: token([238, 20, 63]), 500: token([238, 23, 56]), 600: token([238, 24, 49]), 700: token([238, 28, 38]), 800: token([238, 28, 29]), 900: token([238, 28, 22]), 1000: token([238, 28, 14]), }, ice: { 50: token([211, 100, 97]), 100: token([211, 58, 90]), 200: token([211, 53, 81]), 300: token([211, 49, 70]), 400: token([211, 47, 62]), 500: token([211, 47, 53]), 600: token([211, 56, 44]), 700: token([211, 69, 34]), 800: token([211, 69, 27]), 900: token([211, 100, 20]), 1000: token([211, 100, 14]), }, coolGray: { 50: token([211, 20, 96]), 100: token([211, 20, 90]), 200: token([211, 20, 81]), 300: token([211, 20, 72]), 400: token([211, 20, 61]), 500: token([211, 20, 53]), 600: token([211, 20, 44]), 700: token([211, 23, 36]), 800: token([211, 30, 28]), 900: token([211, 40, 22]), 1000: token([211, 63, 14]), }, tan: { 50: token([41, 23, 96]), 100: token([41, 22, 91]), 200: token([41, 27, 82]), 300: token([41, 23, 68]), 400: token([41, 23, 58]), 500: token([41, 20, 47]), 600: token([41, 20, 40]), 700: token([41, 20, 32]), 800: token([41, 23, 26]), 900: token([41, 23, 21]), 1000: token([41, 22, 16]), }, construction: { 50: token([198, 36, 96]), 100: token([198, 20, 91]), 200: token([198, 14, 82]), 300: token([198, 10, 71]), 400: token([198, 9, 56]), 500: token([198, 10, 46]), 600: token([198, 14, 36]), 700: token([198, 19, 28]), 800: token([198, 23, 23]), 900: token([198, 28, 18]), 1000: token([198, 30, 15]), }, gray: { 0: token([0, 0, 100]), 50: token([0, 0, 98]), 100: token([0, 0, 95]), 200: token([0, 0, 91]), 300: token([0, 0, 87]), 400: token([0, 0, 80]), 500: token([0, 0, 70]), 600: token([0, 0, 55]), 700: token([0, 0, 40]), 800: token([0, 0, 27]), 900: token([0, 0, 20]), 1000: token([0, 0, 0]), }, }; const typography = { color: { 100: token(color.white), 200: token(color.construction[600]), // placeholders 300: token(color.construction[800]), // labels 400: token(color.construction[900]), // headings 500: token(color.black), // content }, fontWeight: { // Clarity City is limited to a minimum weight of 300 and max weight of 600, tokens provide hooks for customization light: token('300'), regular: token('400'), medium: token('500'), semibold: token('600'), bold: token('600'), extrabold: token('600'), }, fontSize: { 0: token(10), 1: token(11), 2: token(12), 3: token(13), 4: token(14), 5: token(16), 6: token(20), 7: token(24), 8: token(32), 9: token(40), }, baseFontSize: token('125%'), // deprecated for removal in 6.0 baseFontSizePx: token(20), // deprecated for removal in 6.0 fontFamily: token("'Clarity City', 'Avenir Next', sans-serif"), headerFontFamily: token("'Clarity City', 'Avenir Next', sans-serif"), monospaceFontFamily: token('ui-monospace, Consolas, Menlo, Monaco, monospace'), topGapHeight: token('0.1475em'), // line-height eraser ascenderHeight: token('0.1703em'), // line-height eraser xHeight: token('0.517em'), // line-height eraser link: { color: { value: token(color.blue[800]), hover: token(color.blue[900]), visited: { value: token(color.lavender[600]), hover: token(color.lavender[700]), }, }, }, body: { fontSize: token(14), lineHeight: token('1.42857em', { static: true }), // static for line height eraser calcs letterSpacing: token('-0.014286em'), fontWeight: token('400'), }, display: { fontSize: token(40), lineHeight: token('1.1em', { static: true }), letterSpacing: token('-0.0125em'), fontWeight: token('400'), }, heading: { fontSize: token(32), lineHeight: token('1.125em', { static: true }), letterSpacing: token('-0.0125em'), fontWeight: token('400'), }, title: { fontSize: token(24), lineHeight: token('1.16667em', { static: true }), letterSpacing: token('-0.008333em'), fontWeight: token('400'), }, section: { fontSize: token(20), lineHeight: token('1.2em', { static: true }), letterSpacing: token('-0.01em'), fontWeight: token('400'), }, subsection: { fontSize: token(16), lineHeight: token('1.25em', { static: true }), letterSpacing: token('-0.0125em'), fontWeight: token('400'), }, message: { fontSize: token(16), lineHeight: token('1.25em', { static: true }), letterSpacing: token('-0.0125em'), fontWeight: token(400), }, secondary: { fontSize: token(13), lineHeight: token('1.23077em', { static: true }), letterSpacing: token('-0.007692em'), fontWeight: token('400'), }, caption: { fontSize: token(11), lineHeight: token('1.454545em', { static: true }), letterSpacing: token('0.018182em'), fontWeight: token('400'), }, smallcaption: { fontSize: token(10), lineHeight: token('1.2em', { static: true }), letterSpacing: token('0.05em'), fontWeight: token('500'), }, }; const animation = { duration: { instant: token('0s'), quickest: token('0.1s'), quicker: token('0.15s'), quick: token('0.2s'), secondary: token('0.3s'), primary: token('0.4s'), slow: token('0.5s'), slower: token('0.7s'), slowest: token('0.8s'), }, easing: { primary: token('cubic-bezier(0,.99,0,.99)'), secondary: token('cubic-bezier(0, 1.5, 0.5, 1)'), loop: token('cubic-bezier(0.17, 0.4, 0.8, 0.79)'), }, }; const aliases = { object: { border: { radius: { 100: token(4), 200: token(12), 300: token('50%'), }, width: { 100: token(1), 200: token(2), 300: token(3), 400: token(4), }, color: { value: token(color.construction[200]), tint: token(color.construction[100]), shade: token(color.construction[300]), }, }, shadow: { 100: token('0 1px 3px 0 hsla(198, 30%, 15%, 0.5)'), 200: token('0 1px 3px 0 hsla(198, 30%, 15%, 0.3)'), 300: token('0 1px 3px 0 hsla(198, 30%, 15%, 0.2)'), }, opacity: { 0: token('hsla(0, 0%, 0%, 0)'), 100: token('hsla(0, 0%, 0%, 0.2)'), 200: token('hsla(0, 0%, 0%, 0.4)'), 300: token('hsla(0, 0%, 0%, 0.6)'), }, interaction: { outline: token('Highlight solid 2px'), outlineOffset: token('1px'), touchTarget: token(36), borderColor: token(color.construction[500]), background: { value: token(color.white), hover: token(color.blue[50]), active: token(color.blue[100]), selected: token(color.blue[50]), disabled: token(color.white), highlight: token(color.blue[700]), }, color: { value: token(color.construction[700]), hover: token(color.construction[1000]), active: token(color.construction[1000]), selected: token(color.construction[700]), disabled: token(color.construction[300]), }, }, app: { background: token(color.gray[50]), }, overlay: { background: token(color.white), backdropBackground: token('hsla(0, 0%, 0%, 0.6)'), }, container: { background: { value: token(color.white), tint: token(color.construction[50]), shade: token(color.construction[100]), }, borderColor: token(color.construction[200]), }, }, status: { info: { value: token(color.blue[700]), tint: token(color.blue[50]), shade: token(color.blue[800]), }, success: { value: token(color.green[700]), tint: token(color.green[50]), shade: token(color.green[800]), }, warning: { value: token(color.ochre[500]), tint: token(color.ochre[100]), shade: token(color.ochre[600]), dark: token(color.ochre[800]), }, danger: { value: token(color.red[700]), tint: token(color.red[50]), shade: token(color.red[800]), }, neutral: { value: token(color.construction[600]), tint: token(color.construction[50]), shade: token(color.construction[700]), }, disabled: { value: token(color.construction[300]), tint: token(color.construction[200]), shade: token(color.construction[400]), }, alt: { value: token(color.violet[700]), tint: token(color.violet[600]), shade: token(color.violet[900]), }, }, }; export const baseTheme: CdsTheme = { global: { layout, space, color, typography, animation, base: token(20, { static: true }) }, aliases, };
the_stack
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { Action, Store } from '@ngrx/store'; import { combineLatest, Observable, of } from 'rxjs'; import { catchError, first, flatMap, map, mergeMap, withLatestFrom } from 'rxjs/operators'; import { environment } from '../../../../core/src/environments/environment'; import { EndpointActionComplete, GET_ENDPOINTS_SUCCESS, GetAllEndpointsSuccess, REGISTER_ENDPOINTS_SUCCESS, UNREGISTER_ENDPOINTS_SUCCESS, UnregisterEndpoint, } from '../../../../store/src/actions/endpoint.actions'; import { ClearPaginationOfType, ResetPaginationOfType } from '../../../../store/src/actions/pagination.actions'; import { EntitySchema } from '../../../../store/src/helpers/entity-schema'; import { isJetstreamError } from '../../../../store/src/jetstream'; import { AppState, EndpointModel, entityCatalog, NormalizedResponse, WrapperRequestActionSuccess, } from '../../../../store/src/public-api'; import { ApiRequestTypes } from '../../../../store/src/reducers/api-request-reducer/request-helpers'; import { endpointOfTypeSelector } from '../../../../store/src/selectors/endpoint.selectors'; import { stratosEntityCatalog } from '../../../../store/src/stratos-entity-catalog'; import { EntityRequestAction, StartRequestAction, WrapperRequestActionFailed, } from '../../../../store/src/types/request.types'; import { helmEntityCatalog } from '../helm-entity-catalog'; import { HELM_ENDPOINT_TYPE, HELM_HUB_ENDPOINT_TYPE, HELM_REPO_ENDPOINT_TYPE } from '../helm-entity-factory'; import { Chart } from '../monocular/shared/models/chart'; import { stratosMonocularEndpointGuid } from '../monocular/stratos-monocular.helper'; import { GET_HELM_VERSIONS, GET_MONOCULAR_CHART_VERSIONS, GET_MONOCULAR_CHARTS, GetHelmChartVersions, GetHelmVersions, GetMonocularCharts, HELM_INSTALL, HELM_SYNCHRONISE, HelmInstall, HelmSynchronise, } from './helm.actions'; import { HelmVersion } from './helm.types'; type MonocularChartsResponse = { data: Chart[]; }; const mapMonocularChartResponse = ( entityKey: string, response: MonocularChartsResponse, schema: EntitySchema ): NormalizedResponse => { const base: NormalizedResponse = { entities: { [entityKey]: {} }, result: [] }; const items = response.data as Array<any>; const processedData: NormalizedResponse = items.reduce((res, data) => { const id = schema.getId(data); res.entities[entityKey][id] = data; // Promote the name to the top-level object for simplicity data.name = data.attributes.name; res.result.push(id); return res; }, base); return processedData; }; const mergeMonocularChartResponses = ( entityKey: string, responses: MonocularChartsResponse[], schema: EntitySchema ): NormalizedResponse => { const combined = responses.reduce((res, response) => { res.data = res.data.concat(response.data); return res; }, { data: [] }); return mapMonocularChartResponse(entityKey, combined, schema); }; const addMonocularId = (endpointId: string, response: MonocularChartsResponse): MonocularChartsResponse => { const data = response.data.map(chart => ({ ...chart, monocularEndpointId: endpointId })); return { data }; }; @Injectable() export class HelmEffects { constructor( private httpClient: HttpClient, private actions$: Actions, private store: Store<AppState>, public snackBar: MatSnackBar, ) { } // Endpoints that we know are synchronizing private syncing = {}; private syncTimer = null; proxyAPIVersion = environment.proxyAPIVersion; // Ensure that we refresh the charts when a repository finishes synchronizing @Effect() updateOnSyncFinished$ = this.actions$.pipe( ofType<GetAllEndpointsSuccess>(GET_ENDPOINTS_SUCCESS), flatMap(action => { // Look to see if we have any endpoints that are synchronizing let updated = false; Object.values(action.payload.entities.stratosEndpoint).forEach(endpoint => { if (endpoint.cnsi_type === HELM_ENDPOINT_TYPE && endpoint.endpoint_metadata) { if (endpoint.endpoint_metadata.status === 'Synchronizing') { // An endpoint is busy, so add it to the list to be monitored if (!this.syncing[endpoint.guid]) { this.syncing[endpoint.guid] = true; updated = true; } } } }); if (updated) { // Schedule check this.scheduleSyncStatusCheck(); } return []; }) ); @Effect() fetchCharts$ = this.actions$.pipe( ofType<GetMonocularCharts>(GET_MONOCULAR_CHARTS), withLatestFrom(this.store), flatMap(([action, appState]) => { const entityKey = entityCatalog.getEntityKey(action); this.store.dispatch(new StartRequestAction(action)); const helmEndpoints = Object.values(endpointOfTypeSelector(HELM_ENDPOINT_TYPE)(appState)); const helmHubEndpoint = helmEndpoints.find(endpoint => endpoint.sub_type === HELM_HUB_ENDPOINT_TYPE); // See https://github.com/SUSE/stratos/issues/466. It would be better to use the standard proxy for this request and go out to all // valid helm sub types instead of making two requests here return combineLatest([ this.createHelmRepoRequest(helmEndpoints), this.createHelmHubRequest(helmHubEndpoint) ]).pipe( map(res => mergeMonocularChartResponses(entityKey, res, action.entity[0])), mergeMap((response: NormalizedResponse) => [new WrapperRequestActionSuccess(response, action)]), catchError(error => { const { status, message } = HelmEffects.createHelmError(error); const endpointIds = helmEndpoints.map(e => e.guid); if (helmHubEndpoint) { endpointIds.push(helmHubEndpoint.guid); } return [ new WrapperRequestActionFailed(message, action, 'fetch', { endpointIds, url: null, eventCode: status, message, error }) ]; }) ); }) ); @Effect() fetchVersions$ = this.actions$.pipe( ofType<GetHelmVersions>(GET_HELM_VERSIONS), flatMap(action => { const entityKey = entityCatalog.getEntityKey(action); return this.makeRequest(action, `/pp/${this.proxyAPIVersion}/helm/versions`, (response) => { const processedData: NormalizedResponse = { entities: { [entityKey]: {} }, result: [] }; // Go through each endpoint ID Object.keys(response).forEach(endpoint => { const endpointData = response[endpoint] || {}; if (isJetstreamError(endpointData)) { throw endpointData; } // Maintain typing const version: HelmVersion = { endpointId: endpoint, ...endpointData }; processedData.entities[entityKey][action.entity[0].getId(version)] = version; processedData.result.push(endpoint); }); return processedData; }, []); }) ); @Effect() fetchChartVersions$ = this.actions$.pipe( ofType<GetHelmChartVersions>(GET_MONOCULAR_CHART_VERSIONS), flatMap(action => { const entityKey = entityCatalog.getEntityKey(action); return this.makeRequest(action, `/pp/${this.proxyAPIVersion}/chartsvc/v1/charts/${action.repoName}/${action.chartName}/versions`, (response) => { const base: NormalizedResponse = { entities: { [entityKey]: {} }, result: [] }; const items = response.data as Array<any>; const processedData = items.reduce((res, data) => { const id = action.entity[0].getId(data); res.entities[entityKey][id] = data; // Promote the name to the top-level object for simplicity data.name = data.attributes.name; res.result.push(id); return res; }, base); return processedData; }, [], { 'x-cap-cnsi-list': action.monocularEndpoint && action.monocularEndpoint !== stratosMonocularEndpointGuid ? action.monocularEndpoint : '' }); }) ); @Effect() helmInstall$ = this.actions$.pipe( ofType<HelmInstall>(HELM_INSTALL), flatMap(action => { const requestType: ApiRequestTypes = 'create'; const url = '/pp/v1/helm/install'; this.store.dispatch(new StartRequestAction(action, requestType)); return this.httpClient.post(url, action.values).pipe( mergeMap(() => { return [ new ClearPaginationOfType(action), new WrapperRequestActionSuccess(null, action) ]; }), catchError(error => { const { status, message } = HelmEffects.createHelmError(error); const errorMessage = `Failed to install helm chart: ${message}`; return [ new WrapperRequestActionFailed(errorMessage, action, requestType, { endpointIds: [action.values.endpoint], url: error.url || url, eventCode: status, message: errorMessage, error }) ]; }) ); }) ); @Effect() helmSynchronise$ = this.actions$.pipe( ofType<HelmSynchronise>(HELM_SYNCHRONISE), flatMap(action => { const requestArgs = { headers: null, params: null }; const proxyAPIVersion = environment.proxyAPIVersion; const url = `/pp/${proxyAPIVersion}/chartrepos/${action.endpoint.guid}`; const req = this.httpClient.post(url, requestArgs); req.subscribe(ok => { this.snackBar.open('Helm Repository synchronization started', 'Dismiss', { duration: 3000 }); }, err => { this.snackBar.open(`Failed to Synchronize Helm Repository '${action.endpoint.name}'`, 'Dismiss', { duration: 5000 }); }); return []; }) ); @Effect() endpointUnregister$ = this.actions$.pipe( ofType<UnregisterEndpoint>(UNREGISTER_ENDPOINTS_SUCCESS), flatMap(action => stratosEntityCatalog.endpoint.store.getEntityMonitor(action.guid).entity$.pipe( first(), mergeMap(endpoint => { if (endpoint.cnsi_type !== HELM_ENDPOINT_TYPE) { return []; } return [ new ResetPaginationOfType(helmEntityCatalog.chart.getSchema()), new ResetPaginationOfType(helmEntityCatalog.chartVersions.getSchema()), new ResetPaginationOfType(helmEntityCatalog.version.getSchema()), ]; }) )) ); @Effect() registerEndpoint$ = this.actions$.pipe( ofType<EndpointActionComplete>(REGISTER_ENDPOINTS_SUCCESS), flatMap(action => { const endpoint: EndpointModel = action.endpoint as EndpointModel; if (endpoint && endpoint.cnsi_type === HELM_ENDPOINT_TYPE && endpoint.sub_type === HELM_HUB_ENDPOINT_TYPE) { return [ new ResetPaginationOfType(helmEntityCatalog.chart.getSchema()), ]; } return []; }) ); private static createHelmErrorMessage(err: any): string { if (err) { if (err.error && err.error.message) { // Kube error return err.error.message; } else if (err.message) { // Http error return err.message; } else if (err.error.status) { // Jetstream error return err.error.status; } } return 'Helm API request error'; } public static createHelmError(err: any): { status: string, message: string, } { let unwrapped = err; if (err.error) { unwrapped = err.error; } const jetstreamError = isJetstreamError(unwrapped); if (jetstreamError) { // Wrapped error return { status: jetstreamError.error.statusCode.toString(), message: HelmEffects.createHelmErrorMessage(jetstreamError) }; } return { status: err && err.status ? err.status + '' : '500', message: this.createHelmErrorMessage(err) }; } private createHelmHubRequest(helmHubEndpoint: EndpointModel): Observable<MonocularChartsResponse> { return helmHubEndpoint ? this.httpClient.get<MonocularChartsResponse>(`/pp/${this.proxyAPIVersion}/chartsvc/v1/charts`, { headers: { 'x-cap-cnsi-list': helmHubEndpoint.guid } }).pipe(map(res => addMonocularId(helmHubEndpoint.guid, res))) : of({ data: [] }); } private createHelmRepoRequest(helmEndpoints: EndpointModel[]): Observable<MonocularChartsResponse> { const helmRepoEndpoints = helmEndpoints.find(endpoint => endpoint.sub_type === HELM_REPO_ENDPOINT_TYPE); return helmRepoEndpoints ? this.httpClient.get<MonocularChartsResponse>(`/pp/${this.proxyAPIVersion}/chartsvc/v1/charts`) : of({ data: [] }); } private makeRequest( action: EntityRequestAction, url: string, mapResult: (response: any) => NormalizedResponse, endpointIds: string[], headers = {} ): Observable<Action> { this.store.dispatch(new StartRequestAction(action)); const requestArgs = { headers, params: null }; return this.httpClient.get(url, requestArgs).pipe( mergeMap((response: any) => [new WrapperRequestActionSuccess(mapResult(response), action)]), catchError(error => { const { status, message } = HelmEffects.createHelmError(error); return [ new WrapperRequestActionFailed(message, action, 'fetch', { endpointIds, url: error.url || url, eventCode: status, message, error }) ]; }) ); } private checkSyncStatus() { // Dispatch request const url = `/pp/${this.proxyAPIVersion}/chartrepos/status`; const requestArgs = { headers: null, params: null }; const req = this.httpClient.post(url, this.syncing, requestArgs); req.subscribe(data => { if (data) { const existing = Object.keys(data).length; const syncing = {}; Object.keys(data).forEach(guid => { if (data[guid]) { syncing[guid] = true; } }); const remaining = Object.keys(syncing).length; this.syncing = syncing; if (remaining !== existing) { // Dispatch action to refresh charts helmEntityCatalog.chart.api.getMultiple(); } if (remaining > 0) { this.scheduleSyncStatusCheck(); } } }); } private scheduleSyncStatusCheck() { if (this.syncTimer !== null) { clearTimeout(this.syncTimer); this.syncTimer = null; } this.syncTimer = setTimeout(() => this.checkSyncStatus(), 5000); } }
the_stack
import { Ticker } from 'pixi.js'; import { trace } from '../utils/trace'; import { EngineView } from '../map/EngineView'; import { ObjectView } from '../map/ObjectView'; import { GridNode } from '../pathFinding/GridNode'; import { getDist, getUnit } from '../utils/calculations'; import { EasingFunction, EasingType, getEasingFunc } from '../utils/easing'; import { TColumnRowPair, TPositionPair } from '../utils/map'; export interface IMovable extends ObjectView { // [key: string]: any, speedUnit: TPositionPair; speedMagnitude: number; currentPath: GridNode[]; currentPathStep: number; currentTarget: TPositionPair; currentTargetTile: GridNode; currentReachThresh: number; prevPosition: TPositionPair; } export interface ITween { target: { [key: string]: unknown }; duration: number; delay: number; easingFunc: EasingFunction; overwrite: boolean; onComplete: () => void; totalFrames: number; currentFrame: number; vars: { [key: string]: { b: number; c: number } }; } export interface ITweenTarget { [key: string]: unknown; tweens?: ITween[]; } /** * Holds and manages all the logic for tween animations and map-object movement on the map. * This is created and used by EngineView instances. * * @class MoveEngine */ export class MoveEngine { /** * A reference to the engine view that uses this move engine. * @property * @private */ private _engine: EngineView; /** * The speed value to be used for object movements if not defined specifically. * @property * @private * @default `3` */ private _defaultSpeed: number; /** * Specifies if the move-engine will process the object movements. * @property * @private * @default `false` */ private _activeForMovables: boolean = false; /** * Specifies if the move-engine will process the tweens. * @property * @private * @default `false` */ private _activeForTweens: boolean = false; /** * Specifies if the move-engine will process the tweens and object movements. * @property * @private * @default `true` */ private _processFrame: boolean = true; /** * The list to store current map-objects in move. * @property * @private * @default `[]` */ private _movables: IMovable[] = []; /** * The list to store targets for the current tweens. * @property * @private * @default `[]` */ private _tweenTargets: ITweenTarget[] = []; /** * Used to calculate how many frames a tween will take to process. * @property * @private * @default `60` */ private _fps: number = 60; private _ticker: Ticker; private _processFunc: () => void; /** * Constructor function for MoveEngine. * * @constructor * * @param engine {EngineView} the engine instance that the animations will perform on * @param defaultSpeed {number} default speed for the map-objects to be used when they move on map, default 3 */ constructor(engine: EngineView, defaultSpeed: number = 3) { this._engine = engine; this._defaultSpeed = defaultSpeed; this._processFunc = this.run.bind(this); this._ticker = new Ticker(); this._ticker.add(this._processFunc); this._ticker.start(); } /** * Adds a single tween for the given object. * * @method * @function * @public * * @param o {ITweenTarget} the object to add tween animation to * @param duration {number} the duration of the tween animation in seconds * @param vars {{ [key: string]: number }} the object defining which properties of the target object will be animated * @param delay {number} the amount of waiting before the tween animation starts, in seconds, default `0` * @param easing {EasingType} type of the easing, default `'linear'` * @param overwrite {boolean} if the other tween animations assigned to the same object are going to be killed, default `false` * @param onComplete {Function} callback function to be called after the tween animation finished, default `null` */ public addTween( o: ITweenTarget, duration: number, vars: { [key: string]: number }, delay: number = 0, easing: EasingType = 'linear', overwrite: boolean = false, onComplete: () => void = null ): void { let v: { [key: string]: { b: number; c: number } } = null; for (const prop in vars) { if (o[prop] !== vars[prop]) { if (!v) { v = {}; } v[prop] = { b: o[prop] as number, c: vars[prop] - (o[prop] as number) }; } } if (v) { const t: ITween = { target: o, duration: duration, delay: Number(delay) || 0, easingFunc: getEasingFunc(easing), overwrite: overwrite || false, onComplete: onComplete || null, totalFrames: duration * this._fps, currentFrame: 0, vars: v, }; const idx = this._tweenTargets.indexOf(o); if (idx >= 0) { let tweens: ITween[] = o.tweens; if (!tweens) { tweens = []; } if (t.overwrite) { for (let i = 0; i < tweens.length; i++) { tweens[i] = null; } tweens = []; } tweens[tweens.length] = t; o.tweens = tweens; } else { o.tweens = [t]; this._tweenTargets[this._tweenTargets.length] = o; } if (this._tweenTargets.length > 0 && !this._activeForTweens) { this._activeForTweens = true; } } } /** * Removes a single tween from the given object. * * @method * @function * @public * * @param o {ITweenTarget} the object to remove the tween animation from * @param t {ITween} the tween to be removed from the object * @return {boolean} if the tween is found and removed */ public removeTween(o: ITweenTarget, t: ITween): boolean { let targetRemoved = false; if (o && t) { const idx = this._tweenTargets.indexOf(o); if (idx >= 0) { if (this._tweenTargets[idx].tweens && this._tweenTargets[idx].tweens.length > 0) { const tweens = this._tweenTargets[idx].tweens; const idx2 = tweens.indexOf(t); if (idx2 >= 0) { t.onComplete = null; t.easingFunc = null; t.target = null; tweens.splice(idx2, 1); if (tweens.length === 0) { this._tweenTargets.splice(idx, 1); targetRemoved = true; } } else { throw new Error('No tween defined for this object'); } } else { throw new Error('No tween defined for this object'); } } else { throw new Error('No tween target defined for this object'); } if (this._tweenTargets.length === 0) { this._activeForTweens = false; } } return targetRemoved; } /** * Removes and kills all tweens assigned to the given object. * * @method * @function * @public * * @param o {ITweenTarget} the object to remove the tween animations from * @return {boolean} if any tween is found and removed from the object specified */ public killTweensOf(o: ITweenTarget): boolean { let targetRemoved = false; const idx = this._tweenTargets.indexOf(o); if (idx >= 0) { if (this._tweenTargets[idx].tweens && this._tweenTargets[idx].tweens.length > 0) { const tweens = this._tweenTargets[idx].tweens; for (let j = 0; j < tweens.length; j++) { tweens[j].onComplete = null; tweens[j].easingFunc = null; tweens[j].target = null; tweens[j] = null; } this._tweenTargets[idx].tweens = null; } this._tweenTargets.splice(idx, 1); targetRemoved = true; } if (this._tweenTargets.length === 0) { this._activeForTweens = false; } return targetRemoved; } /** * Removes and kills all the tweens in operation currently. * * @method * @function * @private */ private removeAllTweens(): void { this._activeForTweens = false; let tweens, i, j; const len = this._tweenTargets.length; for (i = 0; i < len; i++) { tweens = this._tweenTargets[i].tweens; for (j = 0; j < tweens.length; j++) { tweens[j].onComplete = null; tweens[j].easingFunc = null; tweens[j].target = null; tweens[j] = null; } this._tweenTargets[i].tweens = null; this._tweenTargets[i] = null; } this._tweenTargets = []; } /** * Adds a map-object as movable to the engine. * * @method * @function * @public * * @param o {IMovable} the map-object to add as movable */ public addMovable(o: IMovable): void { if (this._movables.indexOf(o) >= 0) { return; } this._movables[this._movables.length] = o; if (this._movables.length > 0 && !this._activeForMovables) { this._activeForMovables = true; } // all movables needs to have the following variables: // speedMagnitude, speedUnit (more to come...) // NOTE: might be a good idea to add all necessary parameters to the object here } /** * Removes a map-object from the current movables list. * * @method * @function * @public * * @param o {IMovable} the map-object to remove * @return {boolean} if the map-object is removed or not */ public removeMovable(o: IMovable): boolean { const idx = this._movables.indexOf(o); if (idx !== -1) { o.speedUnit = { x: 0, y: 0 }; this._movables.splice(idx, 1); } if (this._movables.length === 0) { this._activeForMovables = false; } // TODO: might be a good idea to remove/reset all related parameters from the object here return idx !== -1; } /** * Removes all movables. * * @method * @function * @private */ private removeAllMovables(): void { this._activeForMovables = false; const len = this._movables.length; for (let i = 0; i < len; i++) { this._movables[i] = null; } this._movables = []; } /** * Changes the current path of a map-object. * * @method * @function * @public * * @param o {IMovable} the map-object to add the path to * @param path {Array(GridNode)} the new path * @param speed {number} speed of the map-object to be used during movement, if not defined it uses previous speed or the MoveEngine's default speed, default null */ public addNewPathToObject(o: IMovable, path: GridNode[], speed: number): void { if (o.currentPath && o.currentTarget) { path[path.length] = o.currentPath[o.currentPathStep]; } o.currentPath = path; o.currentPathStep = o.currentPath.length - 1; o.speedMagnitude = speed || o.speedMagnitude || this._defaultSpeed; } /** * Prepares a map-object for movement. * * @method * @function * @public * * @param o {IMovable} the movable map-object * @param path {Array(GridNode)} the path for the object * @param speed {number} speed of the map-object to be used during movement, if not defined it uses previous speed or the MoveEngine's default speed, default null */ public prepareForMove(o: IMovable, path: GridNode[], speed: number = null): void { o.currentPath = path; o.currentPathStep = o.currentPath.length - 1; o.speedMagnitude = speed || o.speedMagnitude || this._defaultSpeed; } /** * Sets movement specific parameters for the map-object according to target location. * * @method * @function * @public * * @param o {IMovable} the movable map-object * @param pos {TColumnRowPair} target location */ public setMoveParameters(o: IMovable, pos: TColumnRowPair): void { const px = this._engine.getTilePosXFor(pos.r, pos.c); const py = this._engine.getTilePosYFor(pos.r, pos.c) + this._engine.tileHalfHeight; o.speedUnit = getUnit({ x: px - o.position.x, y: py - o.position.y }); o.currentTarget = { x: px, y: py }; o.currentReachThresh = Math.ceil( Math.sqrt(o.speedUnit.x * o.speedUnit.x + o.speedUnit.y * o.speedUnit.y) * o.speedMagnitude ); } /** * Method that precesses a single frame. * * @method * @function * @private */ private run(): void { // NOTE: Write an alternative with a real time driven animator if (this._processFrame) { let len: number, o: IMovable, i: number; if (this._activeForMovables) { len = this._movables.length; let dist; for (i = 0; i < len; i++) { o = this._movables[i]; // move object // speed vector (magnitude and direction) o.prevPosition = { x: o.position.x, y: o.position.y }; // check for target reach if (o.currentTarget) { dist = getDist(o.position, o.currentTarget); if (dist <= o.currentReachThresh) { // reached to the target o.position.x = o.currentTarget.x; o.position.y = o.currentTarget.y; this._engine.onObjMoveStepEnd(o); i--; len--; continue; } } o.position.x += o.speedMagnitude * o.speedUnit.x; o.position.y += o.speedMagnitude * o.speedUnit.y; // check for tile change this._engine.checkForTileChange(o); this._engine.checkForFollowCharacter(o); // check for direction change } // will need a different loop to process crashes // for (i=0; i < len; i++) // { // o = this._movables[i]; // } } if (this._activeForTweens) { // and a loop for tween animations len = this._tweenTargets.length; let t: ITween, tt: ITweenTarget, tweens: ITween[], j: number, vars: { [key: string]: { b: number; c: number } }; for (i = 0; i < len; i++) { tt = this._tweenTargets[i]; tweens = tt.tweens; for (j = 0; j < tweens.length; j++) { t = tweens[j]; t.currentFrame++; vars = t.vars; for (const prop in vars) { tt[prop] = t.easingFunc(t.currentFrame, vars[prop].b, vars[prop].c, t.totalFrames); } if (t.currentFrame >= t.totalFrames) { if (t.onComplete) { t.onComplete(); } if (this.removeTween(tt, t)) { i--; len--; } j--; } } } } } } /** * Clears all references and stops all animations and tweens. * * @method * @function * @public */ public destroy(): void { trace('MoveEngine destroy'); this._processFrame = false; if (this._ticker) { this._ticker.stop(); } this.removeAllMovables(); this.removeAllTweens(); this._movables = null; this._tweenTargets = null; this._engine = null; this._ticker = null; } }
the_stack
import { act, fireEvent, wait, waitForElement, RenderResult } from '@testing-library/react'; import { Renderer } from '@gqlapp/testing-client-react'; import POSTS_SUBSCRIPTION from '../graphql/PostsSubscription.graphql'; import POST_SUBSCRIPTION from '../graphql/PostSubscription.graphql'; import COMMENT_SUBSCRIPTION from '../graphql/CommentSubscription.graphql'; const createNode = (id: number) => ({ id, title: `Post title ${id}`, content: `Post content ${id}`, comments: [ { id: id * 1000 + 1, content: 'Post comment 1', __typename: 'Comment' }, { id: id * 1000 + 2, content: 'Post comment 2', __typename: 'Comment' } ], __typename: 'Post' }); const mutations: any = { editPost: () => {}, addComment: () => {}, editComment: () => {}, onCommentSelect: () => {} }; const mocks = { Query: () => ({ posts(ignored: any, { after }: any) { const totalCount = 4; const edges = []; const postId = after < 1 ? +after + 1 : +after; for (let i = postId; i <= postId + 1; i++) { edges.push({ cursor: i, node: createNode(i), __typename: 'PostEdges' }); } return { totalCount, edges, pageInfo: { endCursor: edges[edges.length - 1].cursor, hasNextPage: true, __typename: 'PostPageInfo' }, __typename: 'Posts' }; }, post(obj: any, { id }: any) { return createNode(id); } }), Mutation: () => ({ deletePost: (obj: any, { id }: any) => createNode(id), deleteComment: (obj: any, { input }: any) => input, ...mutations }) }; describe('Posts and comments example UI works', () => { const renderer = new Renderer(mocks, {}); let dom: RenderResult; beforeAll(async () => { dom = renderer.mount(); act(() => { renderer.history.push('/posts'); }); await waitForElement(() => dom.getByText('Post List')); }); it('Posts page renders with data', () => { expect(dom.getByText('Post title 1')).toBeDefined(); expect(dom.getByText('Post title 2')).toBeDefined(); expect(dom.getByText(RegExp(/2[\s]*\/[\s]*4/))).toBeDefined(); }); it('Clicking load more loads more posts', async () => { act(() => { const loadMoreButton = dom.getByText(RegExp('Load more')); fireEvent.click(loadMoreButton); }); await wait(() => { expect(dom.getByText('Post title 3')).toBeDefined(); expect(dom.getByText('Post title 4')).toBeDefined(); expect(dom.getByText(RegExp(/4[\s]*\/[\s]*4/))).toBeDefined(); }); }); it('Check subscribed to post list updates', () => { expect(renderer.getSubscriptions(POSTS_SUBSCRIPTION)).toHaveLength(1); }); it('Updates post list on post delete from subscription', async () => { const subscription = renderer.getSubscriptions(POSTS_SUBSCRIPTION)[0]; act(() => { subscription.next({ data: { postsUpdated: { mutation: 'DELETED', node: createNode(2), __typename: 'UpdatePostPayload' } } }); }); await wait(() => { expect(dom.queryByText('Post title 2')).toBeNull(); expect(dom.getByText(RegExp(/3[\s]*\/[\s]*3/))).toBeDefined(); }); }); it('Updates post list on post create from subscription', async () => { const subscription = renderer.getSubscriptions(POSTS_SUBSCRIPTION)[0]; act(() => { subscription.next({ data: { postsUpdated: { mutation: 'CREATED', node: createNode(2), __typename: 'UpdatePostPayload' } } }); }); await wait(() => { expect(dom.getByText('Post title 2')).toBeDefined(); expect(dom.getByText(RegExp(/4[\s]*\/[\s]*4/))).toBeDefined(); }); }); it('Clicking delete removes the post', async () => { mutations.deletePost = (obj: any, { id }: any) => { return createNode(id); }; const deleteButtons = dom.getAllByText('Delete'); expect(deleteButtons).toHaveLength(4); act(() => { fireEvent.click(deleteButtons[deleteButtons.length - 1]); }); await wait(() => { expect(dom.getByText('Post title 3')).toBeDefined(); expect(dom.queryByText('Post title 4')).toBeNull(); expect(dom.getByText(RegExp(/3[\s]*\/[\s]*3/))).toBeDefined(); }); }); it('Clicking on post opens post form', async () => { const post3 = dom.getByText('Post title 3'); act(() => { fireEvent.click(post3); }); await wait(() => { expect(dom.getByDisplayValue('Post title 3')).toBeDefined(); expect(dom.getByDisplayValue('Post content 3')).toBeDefined(); expect(dom.getByText(/Edit[\s]*Post/)).toBeDefined(); }); }); it('Check subscribed to post updates', () => { expect(renderer.getSubscriptions(POST_SUBSCRIPTION)).toHaveLength(1); }); it('Updates post form when post updated from subscription', async () => { const subscription = renderer.getSubscriptions(POST_SUBSCRIPTION)[0]; act(() => { subscription.next({ data: { postUpdated: { mutation: 'UPDATED', id: 3, node: { id: 3, title: 'Post title 203', content: 'Post content 204', __typename: 'Post' }, __typename: 'UpdatePostPayload' } } }); }); await wait(() => { expect(dom.getByDisplayValue('Post title 203')).toBeDefined(); expect(dom.getByDisplayValue('Post content 204')).toBeDefined(); }); }); it('Opening post by URL works', async () => { act(() => { renderer.history.push('/post/4'); }); await wait(() => { expect(dom.getByText(/Edit[\s]+Post/)).toBeDefined(); expect(dom.getByDisplayValue('Post title 4')).toBeDefined(); expect(dom.getByDisplayValue('Post content 4')).toBeDefined(); }); }); it('Post editing form works', async () => { let values: any; mutations.editPost = (obj: any, { input }: any) => (values = input); // FIXME: `act` should be enabled here and below, when `formik` will support it correctly // act(() => { fireEvent.change(dom.getByPlaceholderText('Title'), { target: { value: 'Post title 44' } }); fireEvent.change(dom.getByPlaceholderText('Content'), { target: { value: 'Post content 44' } }); fireEvent.click(dom.getByText('Update')); // }); await wait(() => { expect(values.id).toEqual(4); expect(values.title).toEqual('Post title 44'); expect(values.content).toEqual('Post content 44'); }); }); it('Comment adding works', async () => { let values: any; mutations.addComment = (obj: any, { input }: any) => (values = input); act(() => { renderer.history.push('/post/4'); }); await wait(() => { expect(dom.getByText(/Edit[\s]+Post/)).toBeDefined(); }); fireEvent.change(dom.getByPlaceholderText('Comment'), { target: { value: 'Post comment 24' } }); fireEvent.click(dom.getByText('Save')); await wait(() => { expect(values.postId).toEqual(4); expect(values.content).toEqual('Post comment 24'); expect(dom.getByText('Post comment 24')).toBeDefined(); }); }); it('Updates comment form on comment added got from subscription', () => { const subscription = renderer.getSubscriptions(COMMENT_SUBSCRIPTION)[0]; act(() => { subscription.next({ data: { commentUpdated: { mutation: 'CREATED', id: 3003, postId: 3, node: { id: 3003, content: 'Post comment 3', __typename: 'Comment' }, __typename: 'UpdateCommentPayload' } } }); }); expect(dom.getByText('Post comment 3')).toBeDefined(); }); it('Updates comment form on comment deleted got from subscription', () => { const subscription = renderer.getSubscriptions(COMMENT_SUBSCRIPTION)[0]; act(() => { subscription.next({ data: { commentUpdated: { mutation: 'DELETED', id: 3003, postId: 3, node: { id: 3003, content: 'Post comment 3', __typename: 'Comment' }, __typename: 'UpdateCommentPayload' } } }); }); expect(dom.queryByText('Post comment 3')).toBeNull(); }); it('Comment deleting removes comment', async () => { const deleteButtons = dom.getAllByText('Delete'); expect(deleteButtons).toHaveLength(3); act(() => { fireEvent.click(deleteButtons[deleteButtons.length - 1]); }); await wait(() => { expect(dom.queryByText('Post comment 24')).toBeNull(); expect(dom.getAllByText('Delete')).toHaveLength(2); }); }); it('Comment editing works', async () => { let values: any; mutations.editComment = (obj: any, { input }: any) => (values = input); const editButtons = dom.getAllByText('Edit'); expect(dom.getByText('Post comment 2')); expect(editButtons).toHaveLength(2); act(() => { fireEvent.click(editButtons[editButtons.length - 1]); }); await waitForElement(() => dom.getByDisplayValue('Post comment 2')); fireEvent.change(dom.getByDisplayValue('Post comment 2'), { target: { value: 'Edited comment 2' } }); fireEvent.submit(dom.getByText('Save')); await wait(() => { expect(values.postId).toEqual(4); expect(values.content).toEqual('Edited comment 2'); }); }); it('Clicking back button takes to post list', async () => { const backButton = dom.getByText('Back'); act(() => { fireEvent.click(backButton); }); const loadMoreButton = await waitForElement(() => dom.getByText(RegExp('Load more'))); act(() => { fireEvent.click(loadMoreButton); }); await waitForElement(() => dom.getByText('Post title 1')); }); });
the_stack
import * as fs from 'fs'; import uri from 'vscode-uri'; import * as path from 'path'; import * as glslx from 'glslx'; import * as server from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; let buildResults: () => Record<string, glslx.CompileResultIDE | undefined> = () => ({}); let openDocuments: server.TextDocuments<TextDocument>; let connection: server.Connection; let timeout: NodeJS.Timeout; function reportErrors(callback: () => void): void { try { callback(); } catch (e) { let message = e && e.stack || e; connection.console.error('glslx: ' + message); connection.window.showErrorMessage('glslx: ' + message); } } function convertRange(range: glslx.Range): server.Range { return { start: { line: range.start.line, character: range.start.column, }, end: { line: range.end.line, character: range.end.column, }, }; } function uriToPath(value: string): string | null { let parsed = uri.parse(value); return parsed.scheme === 'file' ? path.normalize(parsed.fsPath) : null; } function pathToURI(value: string): string { return uri.file(value).toString(); } function sendDiagnostics(diagnostics: glslx.Diagnostic[], unusedSymbols: glslx.UnusedSymbol[]): void { let map: Record<string, server.Diagnostic[]> = {}; for (let diagnostic of diagnostics) { if (!diagnostic.range) continue; let key = diagnostic.range.source; let group = map[key] || (map[key] = []); group.push({ severity: diagnostic.kind === 'error' ? server.DiagnosticSeverity.Error : server.DiagnosticSeverity.Warning, range: convertRange(diagnostic.range), message: diagnostic.text, }); } for (let symbol of unusedSymbols) { let key = symbol.range!.source; let group = map[key] || (map[key] = []); group.push({ severity: server.DiagnosticSeverity.Hint, range: convertRange(symbol.range!), message: `${JSON.stringify(symbol.name)} is never used in this file`, tags: [server.DiagnosticTag.Unnecessary], }); } for (let doc of openDocuments.all()) { connection.sendDiagnostics({ uri: doc.uri, diagnostics: map[doc.uri] || [], }); } } function buildOnce(): Record<string, glslx.CompileResultIDE> { let results: Record<string, glslx.CompileResultIDE> = {}; reportErrors(() => { let unusedSymbols: glslx.UnusedSymbol[] = []; let diagnostics: glslx.Diagnostic[] = []; let docs: Record<string, string> = {}; for (let doc of openDocuments.all()) { docs[doc.uri] = doc.getText(); } function fileAccess(includeText: string, relativeURI: string) { let relativePath = uriToPath(relativeURI); let absolutePath = relativePath ? path.resolve(path.dirname(path.resolve(relativePath)), includeText) : path.resolve(includeText); // In-memory files take precedence let absoluteURI = pathToURI(absolutePath); if (absoluteURI in docs) { return { name: absoluteURI, contents: docs[absoluteURI], }; } // Then try to read from disk try { return { name: absoluteURI, contents: fs.readFileSync(absolutePath, 'utf8'), }; } catch (e) { return null; } } for (let doc of openDocuments.all()) { let result = glslx.compileIDE({ name: doc.uri, contents: docs[doc.uri], }, { fileAccess, }); results[doc.uri] = result; unusedSymbols.push.apply(unusedSymbols, result.unusedSymbols); diagnostics.push.apply(diagnostics, result.diagnostics); } sendDiagnostics(diagnostics, unusedSymbols); }); return results; } function buildLater(): void { buildResults = () => { let result = buildOnce(); buildResults = () => result; return result; }; clearTimeout(timeout); timeout = setTimeout(buildResults, 100); } function computeTooltip(request: server.TextDocumentPositionParams): server.Hover | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.tooltipQuery({ source: request.textDocument.uri, line: request.position.line, column: request.position.character, // Visual Studio Code already includes diagnostics and including // them in the results causes each diagnostic to be shown twice ignoreDiagnostics: true, }); if (response.tooltip !== null && response.range !== null) { return { contents: { kind: 'markdown', value: '```glslx\n' + response.tooltip + '\n```\n' + response.documentation, }, range: convertRange(response.range), } } } } function computeDefinitionLocation(request: server.TextDocumentPositionParams): server.Definition | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.definitionQuery({ source: request.textDocument.uri, line: request.position.line, column: request.position.character, }); if (response.definition !== null) { return { uri: response.definition.source, range: convertRange(response.definition), }; } } } function computeDocumentSymbols(request: server.DocumentSymbolParams): server.SymbolInformation[] | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.symbolsQuery({ source: request.textDocument.uri, }); if (response.symbols !== null) { return response.symbols.map(symbol => { return { name: symbol.name, kind: symbol.kind === 'struct' ? server.SymbolKind.Class : symbol.kind === 'function' ? server.SymbolKind.Function : server.SymbolKind.Variable, location: { uri: symbol.range.source, range: convertRange(symbol.range), }, }; }); } } } function computeRenameEdits(request: server.RenameParams): server.WorkspaceEdit | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.renameQuery({ source: request.textDocument.uri, line: request.position.line, column: request.position.character, }); if (response.ranges !== null) { let documentChanges: server.TextDocumentEdit[] = []; let map: Record<string, server.TextEdit[]> = {}; for (let range of response.ranges) { let edits = map[range.source]; if (!edits) { let doc = openDocuments.get(range.source); edits = map[range.source] = []; if (doc) { documentChanges.push({ textDocument: { uri: range.source, version: doc.version }, edits, }); } } edits.push({ range: convertRange(range), newText: request.newName, }); } return { documentChanges, }; } } } function formatDocument(request: server.DocumentFormattingParams): server.TextEdit[] { let doc = openDocuments.get(request.textDocument.uri) if (!doc) { return []; } let options = request.options || {}; let input = doc.getText(); let output = glslx.format(input, { indent: options.insertSpaces ? ' '.repeat(options.tabSize || 2) : '\t', newline: '\n', // It seems like it's impossible to get the trailing newline settings from // VSCode here? They are always undefined for some reason even though they // are present in the type definitions. It says they are present as of // version 3.15.0 but the published version of "vscode-languageserver" only // goes up to 3.5.0 before 4.0.0. This seems like a bug in VSCode itself: // https://github.com/microsoft/vscode-languageserver-node/issues/617 // // trailingNewline: // options.insertFinalNewline ? 'insert' : // options.trimFinalNewlines ? 'remove' : // 'preserve', // trailingNewline: 'insert', }); // Early-out if nothing changed if (input === output) { return []; } // Just return one big edit. VSCode seems to be smart enough to keep the // cursor in the right place if whitespace between tokens shifts around. return [{ range: { start: { line: 0, character: 0, }, end: doc.positionAt(input.length), }, newText: output, }]; } function computeCompletion(request: server.CompletionParams): server.CompletionItem[] | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.completionQuery({ source: request.textDocument.uri, line: request.position.line, column: request.position.character, }); return response.completions.map(completion => ({ kind: completion.kind === 'struct' ? server.CompletionItemKind.Class : completion.kind === 'function' ? server.CompletionItemKind.Function : completion.kind === 'variable' ? server.CompletionItemKind.Variable : server.CompletionItemKind.Keyword, label: completion.name, documentation: completion.detail === '' ? void 0 : { kind: 'markdown', value: '```glslx\n' + completion.detail + '\n```\n' + completion.documentation, }, })); } } function computeSignature(request: server.SignatureHelpParams): server.SignatureHelp | undefined { let result = buildResults()[request.textDocument.uri]; if (result) { let response = result.signatureQuery({ source: request.textDocument.uri, line: request.position.line, column: request.position.character, }); return { activeSignature: response.activeSignature !== -1 ? response.activeSignature : null, activeParameter: response.activeArgument !== -1 ? response.activeArgument : null, signatures: response.signatures.map(signature => ({ label: signature.text, documentation: signature.documentation === '' ? void 0 : { kind: 'markdown', value: signature.documentation, }, parameters: signature.arguments.map(arg => ({ label: arg, })), })), }; } } function main(): void { connection = server.createConnection( new server.IPCMessageReader(process), new server.IPCMessageWriter(process)); reportErrors(() => { // Listen to open documents openDocuments = new server.TextDocuments(TextDocument); openDocuments.listen(connection); openDocuments.onDidChangeContent(buildLater); // Grab the workspace when the connection opens connection.onInitialize(() => { buildLater(); return { capabilities: { textDocumentSync: server.TextDocumentSyncKind.Incremental, hoverProvider: true, renameProvider: true, definitionProvider: true, documentSymbolProvider: true, documentFormattingProvider: true, signatureHelpProvider: { triggerCharacters: ['(', ','], }, completionProvider: { triggerCharacters: ['.'], }, }, }; }); // Show tooltips on hover connection.onHover(request => { let tooltip: server.Hover | undefined; reportErrors(() => { tooltip = computeTooltip(request); }); return tooltip!; }); // Support the "go to definition" feature connection.onDefinition(request => { let location: server.Definition | undefined; reportErrors(() => { location = computeDefinitionLocation(request); }) return location!; }); // Support the go to symbol feature connection.onDocumentSymbol(request => { let info: server.SymbolInformation[] | undefined; reportErrors(() => { info = computeDocumentSymbols(request); }); return info!; }); // Support the "rename symbol" feature connection.onRenameRequest(request => { let edits: server.WorkspaceEdit | undefined; reportErrors(() => { edits = computeRenameEdits(request); }); return edits!; }); // Support whole-document formatting connection.onDocumentFormatting(request => { let edits: server.TextEdit[] | undefined; reportErrors(() => { edits = formatDocument(request); }); return edits!; }); // Support symbol completions connection.onCompletion(request => { let result: server.CompletionItem[] | undefined; reportErrors(() => { result = computeCompletion(request); }); return result; }); // Support function signature resolution connection.onSignatureHelp(request => { let result: server.SignatureHelp | undefined; reportErrors(() => { result = computeSignature(request); }); return result; }); // Listen to file system changes for *.glslx files connection.onDidChangeWatchedFiles(buildLater); }); connection.listen(); } main();
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodeType, INodeTypeDescription, } from 'n8n-workflow'; import { adjustAccounts, adjustAttendees, freshworksCrmApiRequest, getAllItemsViewId, handleListing, loadResource, throwOnEmptyFilter, throwOnEmptyUpdate, } from './GenericFunctions'; import { accountFields, accountOperations, appointmentFields, appointmentOperations, contactFields, contactOperations, dealFields, dealOperations, noteFields, noteOperations, salesActivityFields, salesActivityOperations, taskFields, taskOperations, } from './descriptions'; import { FreshworksConfigResponse, LoadedCurrency, LoadedUser, LoadOption, } from './types'; import { tz, } from 'moment-timezone'; export class FreshworksCrm implements INodeType { description: INodeTypeDescription = { displayName: 'Freshworks CRM', name: 'freshworksCrm', icon: 'file:freshworksCrm.svg', group: ['transform'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume the Freshworks CRM API', defaults: { name: 'Freshworks CRM', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'freshworksCrmApi', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Account', value: 'account', }, { name: 'Appointment', value: 'appointment', }, { name: 'Contact', value: 'contact', }, { name: 'Deal', value: 'deal', }, { name: 'Note', value: 'note', }, { name: 'Sales Activity', value: 'salesActivity', }, { name: 'Task', value: 'task', }, ], default: 'account', }, ...accountOperations, ...accountFields, ...appointmentOperations, ...appointmentFields, ...contactOperations, ...contactFields, ...dealOperations, ...dealFields, ...noteOperations, ...noteFields, ...salesActivityOperations, ...salesActivityFields, ...taskOperations, ...taskFields, ], }; methods = { loadOptions: { async getAccounts(this: ILoadOptionsFunctions) { const viewId = await getAllItemsViewId.call(this, { fromLoadOptions: true }); const responseData = await handleListing.call(this, 'GET', `/sales_accounts/view/${viewId}`); return responseData.map(({ name, id }) => ({ name, value: id })) as LoadOption[]; }, async getAccountViews(this: ILoadOptionsFunctions) { const responseData = await handleListing.call(this, 'GET', '/sales_accounts/filters'); return responseData.map(({ name, id }) => ({ name, value: id })) as LoadOption[]; }, async getBusinessTypes(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'business_types'); }, async getCampaigns(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'campaigns'); }, async getContactStatuses(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'contact_statuses'); }, async getContactViews(this: ILoadOptionsFunctions) { const responseData = await handleListing.call(this, 'GET', '/contacts/filters'); return responseData.map(({ name, id }) => ({ name, value: id })) as LoadOption[]; }, async getCurrencies(this: ILoadOptionsFunctions) { const response = await freshworksCrmApiRequest.call( this, 'GET', '/selector/currencies', ) as FreshworksConfigResponse<LoadedCurrency>; const key = Object.keys(response)[0]; return response[key].map(({ currency_code, id }) => ({ name: currency_code, value: id })); }, async getDealPaymentStatuses(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_payment_statuses'); }, async getDealPipelines(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_pipelines'); }, async getDealProducts(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_products'); }, async getDealReasons(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_reasons'); }, async getDealStages(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_stages'); }, async getDealTypes(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'deal_types'); }, async getDealViews(this: ILoadOptionsFunctions) { const responseData = await handleListing.call(this, 'GET', '/deals/filters'); return responseData.map(({ name, id }) => ({ name, value: id })) as LoadOption[]; }, async getIndustryTypes(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'industry_types'); }, async getLifecycleStages(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'lifecycle_stages'); }, async getOutcomes(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'sales_activity_outcomes'); }, async getSalesActivityTypes(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'sales_activity_types'); }, async getTerritories(this: ILoadOptionsFunctions) { return await loadResource.call(this, 'territories'); }, async getUsers(this: ILoadOptionsFunctions) { // for attendees, owners, and creators const response = await freshworksCrmApiRequest.call( this, 'GET', `/selector/owners`, ) as FreshworksConfigResponse<LoadedUser>; const key = Object.keys(response)[0]; return response[key].map( ({ display_name, id }) => ({ name: display_name, value: id }), ); }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; const defaultTimezone = this.getTimezone(); let responseData; for (let i = 0; i < items.length; i++) { try { if (resource === 'account') { // ********************************************************************** // account // ********************************************************************** // https://developers.freshworks.com/crm/api/#accounts if (operation === 'create') { // ---------------------------------------- // account: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_account const body = { name: this.getNodeParameter('name', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, additionalFields); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/sales_accounts', body); responseData = responseData.sales_account; } else if (operation === 'delete') { // ---------------------------------------- // account: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_account const accountId = this.getNodeParameter('accountId', i); const endpoint = `/sales_accounts/${accountId}`; await freshworksCrmApiRequest.call(this, 'DELETE', endpoint); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // account: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_account const accountId = this.getNodeParameter('accountId', i); const endpoint = `/sales_accounts/${accountId}`; responseData = await freshworksCrmApiRequest.call(this, 'GET', endpoint); responseData = responseData.sales_account; } else if (operation === 'getAll') { // ---------------------------------------- // account: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_accounts const view = this.getNodeParameter('view', i) as string; responseData = await handleListing.call(this, 'GET', `/sales_accounts/view/${view}`); } else if (operation === 'update') { // ---------------------------------------- // account: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_account const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (Object.keys(updateFields).length) { Object.assign(body, updateFields); } else { throwOnEmptyUpdate.call(this, resource); } const accountId = this.getNodeParameter('accountId', i); const endpoint = `/sales_accounts/${accountId}`; responseData = await freshworksCrmApiRequest.call(this, 'PUT', endpoint, body); responseData = responseData.sales_account; } } else if (resource === 'appointment') { // ********************************************************************** // appointment // ********************************************************************** // https://developers.freshworks.com/crm/api/#appointments if (operation === 'create') { // ---------------------------------------- // appointment: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_appointment const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject & { time_zone: string; is_allday: boolean; }; const startDate = this.getNodeParameter('fromDate', i) as string; const endDate = this.getNodeParameter('endDate', i) as string; const attendees = this.getNodeParameter('attendees.attendee', i, []) as [{ type: string, contactId: string, userId: string }]; const timezone = additionalFields.time_zone ?? defaultTimezone; let allDay = false; if (additionalFields.is_allday) { allDay = additionalFields.is_allday as boolean; } const start = tz(startDate, timezone); const end = tz(endDate, timezone); const body = { title: this.getNodeParameter('title', i), from_date: start.format(), end_date: (allDay) ? start.format() : end.format(), } as IDataObject; Object.assign(body, additionalFields); if (attendees.length) { body['appointment_attendees_attributes'] = adjustAttendees(attendees); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/appointments', body); responseData = responseData.appointment; } else if (operation === 'delete') { // ---------------------------------------- // appointment: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_appointment const appointmentId = this.getNodeParameter('appointmentId', i); const endpoint = `/appointments/${appointmentId}`; await freshworksCrmApiRequest.call(this, 'DELETE', endpoint); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // appointment: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_a_appointment const appointmentId = this.getNodeParameter('appointmentId', i); const endpoint = `/appointments/${appointmentId}`; responseData = await freshworksCrmApiRequest.call(this, 'GET', endpoint); responseData = responseData.appointment; } else if (operation === 'getAll') { // ---------------------------------------- // appointment: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_appointments const { filter, include } = this.getNodeParameter('filters', i) as { filter: string; include: string[]; }; const qs: IDataObject = {}; if (filter) { qs.filter = filter; } if (include) { qs.include = include; } responseData = await handleListing.call(this, 'GET', '/appointments', {}, qs); } else if (operation === 'update') { // ---------------------------------------- // appointment: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_appointment const updateFields = this.getNodeParameter('updateFields', i) as IDataObject & { from_date: string; end_date: string; time_zone: string; }; const attendees = this.getNodeParameter('updateFields.attendees.attendee', i, []) as [{ type: string, contactId: string, userId: string }]; if (!Object.keys(updateFields).length) { throwOnEmptyUpdate.call(this, resource); } const body = {} as IDataObject; const { from_date, end_date, ...rest } = updateFields; const timezone = rest.time_zone ?? defaultTimezone; if (from_date) { body.from_date = tz(from_date, timezone).format(); } if (end_date) { body.end_date = tz(end_date, timezone).format(); } Object.assign(body, rest); if (attendees.length) { body['appointment_attendees_attributes'] = adjustAttendees(attendees); delete body.attendees; } const appointmentId = this.getNodeParameter('appointmentId', i); const endpoint = `/appointments/${appointmentId}`; responseData = await freshworksCrmApiRequest.call(this, 'PUT', endpoint, body); responseData = responseData.appointment; } } else if (resource === 'contact') { // ********************************************************************** // contact // ********************************************************************** // https://developers.freshworks.com/crm/api/#contacts if (operation === 'create') { // ---------------------------------------- // contact: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_contact const body = { first_name: this.getNodeParameter('firstName', i), last_name: this.getNodeParameter('lastName', i), emails: this.getNodeParameter('emails', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, adjustAccounts(additionalFields)); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/contacts', body); responseData = responseData.contact; } else if (operation === 'delete') { // ---------------------------------------- // contact: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_contact const contactId = this.getNodeParameter('contactId', i); const endpoint = `/contacts/${contactId}`; await freshworksCrmApiRequest.call(this, 'DELETE', endpoint); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // contact: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_a_contact const contactId = this.getNodeParameter('contactId', i); const endpoint = `/contacts/${contactId}`; responseData = await freshworksCrmApiRequest.call(this, 'GET', endpoint); responseData = responseData.contact; } else if (operation === 'getAll') { // ---------------------------------------- // contact: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_contacts const view = this.getNodeParameter('view', i) as string; responseData = await handleListing.call(this, 'GET', `/contacts/view/${view}`); } else if (operation === 'update') { // ---------------------------------------- // contact: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_contact const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (Object.keys(updateFields).length) { Object.assign(body, adjustAccounts(updateFields)); } else { throwOnEmptyUpdate.call(this, resource); } const contactId = this.getNodeParameter('contactId', i); const endpoint = `/contacts/${contactId}`; responseData = await freshworksCrmApiRequest.call(this, 'PUT', endpoint, body); responseData = responseData.contact; } } else if (resource === 'deal') { // ********************************************************************** // deal // ********************************************************************** // https://developers.freshworks.com/crm/api/#deals if (operation === 'create') { // ---------------------------------------- // deal: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_deal const body = { name: this.getNodeParameter('name', i), amount: this.getNodeParameter('amount', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, adjustAccounts(additionalFields)); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/deals', body); responseData = responseData.deal; } else if (operation === 'delete') { // ---------------------------------------- // deal: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_deal const dealId = this.getNodeParameter('dealId', i); await freshworksCrmApiRequest.call(this, 'DELETE', `/deals/${dealId}`); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // deal: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_a_deal const dealId = this.getNodeParameter('dealId', i); responseData = await freshworksCrmApiRequest.call(this, 'GET', `/deals/${dealId}`); responseData = responseData.deal; } else if (operation === 'getAll') { // ---------------------------------------- // deal: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_deals const view = this.getNodeParameter('view', i) as string; responseData = await handleListing.call(this, 'GET', `/deals/view/${view}`); } else if (operation === 'update') { // ---------------------------------------- // deal: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_deal const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (Object.keys(updateFields).length) { Object.assign(body, adjustAccounts(updateFields)); } else { throwOnEmptyUpdate.call(this, resource); } const dealId = this.getNodeParameter('dealId', i); responseData = await freshworksCrmApiRequest.call(this, 'PUT', `/deals/${dealId}`, body); responseData = responseData.deal; } } else if (resource === 'note') { // ********************************************************************** // note // ********************************************************************** // https://developers.freshworks.com/crm/api/#notes if (operation === 'create') { // ---------------------------------------- // note: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_note const body = { description: this.getNodeParameter('description', i), targetable_id: this.getNodeParameter('targetable_id', i), targetable_type: this.getNodeParameter('targetableType', i), } as IDataObject; responseData = await freshworksCrmApiRequest.call(this, 'POST', '/notes', body); responseData = responseData.note; } else if (operation === 'delete') { // ---------------------------------------- // note: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_note const noteId = this.getNodeParameter('noteId', i); await freshworksCrmApiRequest.call(this, 'DELETE', `/notes/${noteId}`); responseData = { success: true }; } else if (operation === 'update') { // ---------------------------------------- // note: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_note const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (Object.keys(updateFields).length) { Object.assign(body, updateFields); } else { throwOnEmptyUpdate.call(this, resource); } const noteId = this.getNodeParameter('noteId', i); responseData = await freshworksCrmApiRequest.call(this, 'PUT', `/notes/${noteId}`, body); responseData = responseData.note; } } else if (resource === 'salesActivity') { // ********************************************************************** // salesActivity // ********************************************************************** // https://developers.freshworks.com/crm/api/#sales-activities if (operation === 'create') { // ---------------------------------------- // salesActivity: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_sales_activity const startDate = this.getNodeParameter('from_date', i) as string; const endDate = this.getNodeParameter('end_date', i) as string; const body = { sales_activity_type_id: this.getNodeParameter('sales_activity_type_id', i), title: this.getNodeParameter('title', i), owner_id: this.getNodeParameter('ownerId', i), start_date: tz(startDate, defaultTimezone).format(), end_date: tz(endDate, defaultTimezone).format(), targetable_type: this.getNodeParameter('targetableType', i), targetable_id: this.getNodeParameter('targetable_id', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, additionalFields); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/sales_activities', { sales_activity: body }); responseData = responseData.sales_activity; } else if (operation === 'delete') { // ---------------------------------------- // salesActivity: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_sales_activity const salesActivityId = this.getNodeParameter('salesActivityId', i); const endpoint = `/sales_activities/${salesActivityId}`; await freshworksCrmApiRequest.call(this, 'DELETE', endpoint); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // salesActivity: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_a_sales_activity const salesActivityId = this.getNodeParameter('salesActivityId', i); const endpoint = `/sales_activities/${salesActivityId}`; responseData = await freshworksCrmApiRequest.call(this, 'GET', endpoint); responseData = responseData.sales_activity; } else if (operation === 'getAll') { // ---------------------------------------- // salesActivity: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_sales_activities responseData = await handleListing.call(this, 'GET', '/sales_activities'); } else if (operation === 'update') { // ---------------------------------------- // salesActivity: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_sales_activity const updateFields = this.getNodeParameter('updateFields', i) as IDataObject & { from_date: string; end_date: string; time_zone: string; }; if (!Object.keys(updateFields).length) { throwOnEmptyUpdate.call(this, resource); } const body = {} as IDataObject; const { from_date, end_date, ...rest } = updateFields; if (from_date) { body.from_date = tz(from_date, defaultTimezone).format(); } if (end_date) { body.end_date = tz(end_date, defaultTimezone).format(); } if (Object.keys(rest).length) { Object.assign(body, rest); } const salesActivityId = this.getNodeParameter('salesActivityId', i); const endpoint = `/sales_activities/${salesActivityId}`; responseData = await freshworksCrmApiRequest.call(this, 'PUT', endpoint, body); responseData = responseData.sales_activity; } } else if (resource === 'task') { // ********************************************************************** // task // ********************************************************************** // https://developers.freshworks.com/crm/api/#tasks if (operation === 'create') { // ---------------------------------------- // task: create // ---------------------------------------- // https://developers.freshworks.com/crm/api/#create_task const dueDate = this.getNodeParameter('dueDate', i); const body = { title: this.getNodeParameter('title', i), owner_id: this.getNodeParameter('ownerId', i), due_date: tz(dueDate, defaultTimezone).format(), targetable_type: this.getNodeParameter('targetableType', i), targetable_id: this.getNodeParameter('targetable_id', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, additionalFields); } responseData = await freshworksCrmApiRequest.call(this, 'POST', '/tasks', body); responseData = responseData.task; } else if (operation === 'delete') { // ---------------------------------------- // task: delete // ---------------------------------------- // https://developers.freshworks.com/crm/api/#delete_a_task const taskId = this.getNodeParameter('taskId', i); await freshworksCrmApiRequest.call(this, 'DELETE', `/tasks/${taskId}`); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // task: get // ---------------------------------------- // https://developers.freshworks.com/crm/api/#view_a_task const taskId = this.getNodeParameter('taskId', i); responseData = await freshworksCrmApiRequest.call(this, 'GET', `/tasks/${taskId}`); responseData = responseData.task; } else if (operation === 'getAll') { // ---------------------------------------- // task: getAll // ---------------------------------------- // https://developers.freshworks.com/crm/api/#list_all_tasks const { filter, include } = this.getNodeParameter('filters', i) as { filter: string; include: string; }; const qs: IDataObject = { filter: 'open', }; if (filter) { qs.filter = filter; } if (include) { qs.include = include; } responseData = await handleListing.call(this, 'GET', '/tasks', {}, qs); } else if (operation === 'update') { // ---------------------------------------- // task: update // ---------------------------------------- // https://developers.freshworks.com/crm/api/#update_a_task const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (!Object.keys(updateFields).length) { throwOnEmptyUpdate.call(this, resource); } const { dueDate, ...rest } = updateFields; if (dueDate) { body.due_date = tz(dueDate, defaultTimezone).format(); } if (Object.keys(rest).length) { Object.assign(body, rest); } const taskId = this.getNodeParameter('taskId', i); responseData = await freshworksCrmApiRequest.call(this, 'PUT', `/tasks/${taskId}`, body); responseData = responseData.task; } } } catch (error) { if (this.continueOnFail()) { returnData.push({ json: { error: error.message } }); continue; } throw error; } Array.isArray(responseData) ? returnData.push(...responseData) : returnData.push(responseData); } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import * as React from "react"; import classnames from "classnames"; import "./Listbox.scss"; import { Guid } from "@itwin/core-bentley"; import { SpecialKey } from "@itwin/appui-abstract"; /** Ideas borrowed from https://reacttraining.com/reach-ui/listbox */ /** * `Listbox` value. * @alpha */ export type ListboxValue = string; /** * `Listbox` Props. * @alpha */ export interface ListboxProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLUListElement>, HTMLUListElement> { id?: string; selectedValue?: ListboxValue; ariaLabel?: any; ariaLabelledBy?: any; onListboxValueChange?: ((newValue: ListboxValue, isControlOrCommandPressed?: boolean) => void); } /** * `ListboxItem` Props. * @alpha */ export interface ListboxItemProps extends React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement> { /** The unique item's value. */ value: ListboxValue; /** set if item is disabled. */ disabled?: boolean; } /** * `Listbox` Context. * @alpha */ export interface ListboxContextProps { listboxId?: string; listboxValue?: ListboxValue; focusValue?: ListboxValue; onListboxValueChange: ((newValue: ListboxValue, isControlOrCommandPressed?: boolean) => void); listboxRef?: React.RefObject<HTMLUListElement>; } /** * Context set up by listbox for use by `ListboxItems` . * @alpha */ // istanbul ignore next export const ListboxContext = React.createContext<ListboxContextProps>({ onListboxValueChange: (_newValue: ListboxValue | undefined) => { } }); // eslint-disable-line @typescript-eslint/naming-convention function makeId(...args: Array<string | number | null | undefined>) { return args.filter((val) => val != null).join("--"); } function getOptionValueArray(childNodes: React.ReactNode): ListboxItemProps[] { return React.Children.toArray(childNodes).filter((node) => React.isValidElement(node) && node.props.value).map((optionNode) => ((optionNode as React.ReactElement).props as ListboxItemProps)); } function processKeyboardNavigation(optionValues: ListboxItemProps[], itemIndex: number, key: string): [number, boolean] { let keyProcessed = false; let newIndex = itemIndex >= 0 ? itemIndex : 0; // Note: In aria example Page Up/Down just moves up or down by one item. See https://www.w3.org/TR/wai-aria-practices-1.1/examples/listbox/js/listbox.js if (key === SpecialKey.ArrowDown || key === SpecialKey.PageDown) { for (let i = itemIndex + 1; i < optionValues.length; i++) { if (!optionValues[i].disabled) { newIndex = i; break; } } keyProcessed = true; } else if (key === SpecialKey.ArrowUp || key === SpecialKey.PageUp) { for (let i = itemIndex - 1; i >= 0; i--) { if (!optionValues[i].disabled) { newIndex = i; break; } } keyProcessed = true; } else if (key === SpecialKey.Home) { for (let i = 0; i < optionValues.length; i++) { if (!optionValues[i].disabled) { newIndex = i; break; } } keyProcessed = true; } else if (key === SpecialKey.End) { for (let i = optionValues.length - 1; i >= 0; i--) { if (!optionValues[i].disabled) { newIndex = i; break; } } keyProcessed = true; } return [newIndex, keyProcessed]; } /** * Single select `Listbox` component * @alpha */ export function Listbox(props: ListboxProps) { const { ariaLabel, ariaLabelledBy, id, children, selectedValue, className, onListboxValueChange, onKeyPress, ...otherProps } = props; const listRef = React.useRef<HTMLUListElement>(null); const [listId] = React.useState(() => { return id ?? Guid.createValue(); }); const optionValues = React.useMemo(() => getOptionValueArray(children), [children]); const classes = React.useMemo(() => classnames("core-listbox", className), [className]); const [currentValue, setCurrentValue] = React.useState<ListboxValue | undefined>(selectedValue); const [focusValue, setFocusValue] = React.useState<ListboxValue | undefined>(currentValue); React.useEffect(() => { setCurrentValue(selectedValue); setFocusValue(selectedValue); }, [selectedValue]); const scrollTopRef = React.useRef(0); const handleValueChange = React.useCallback((newValue: ListboxValue, isControlOrCommandPressed?: boolean) => { // istanbul ignore else if (newValue !== currentValue) { setCurrentValue(newValue); setFocusValue(newValue); if (onListboxValueChange) onListboxValueChange(newValue, isControlOrCommandPressed); } }, [setCurrentValue, currentValue, onListboxValueChange]); const focusOption = React.useCallback((itemIndex: number) => { // istanbul ignore else if (itemIndex >= 0 && itemIndex < optionValues.length) { const newSelection = optionValues[itemIndex]; const listElement = listRef.current as HTMLUListElement; // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const optionToFocus = listElement.querySelector(`li[data-value="${newSelection.value}"]`) as HTMLLIElement | null; // istanbul ignore else if (optionToFocus && listElement) { let newScrollTop = listElement.scrollTop; // istanbul ignore next if (listElement.scrollHeight > listElement.clientHeight) { const scrollBottom = listElement.clientHeight + listElement.scrollTop; const elementBottom = optionToFocus.offsetTop + optionToFocus.offsetHeight; if (elementBottom > scrollBottom) { newScrollTop = elementBottom - listElement.clientHeight; } else if (optionToFocus.offsetTop < listElement.scrollTop) { newScrollTop = optionToFocus.offsetTop; } scrollTopRef.current = newScrollTop; } setFocusValue(newSelection.value); } } }, [optionValues]); const handleKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLUListElement>) => { if (optionValues.length < 1) return; const itemIndex = (undefined === focusValue) ? -1 : optionValues.findIndex((optionValue) => ((optionValue.value === focusValue))); if (event.key === SpecialKey.Space) { event.preventDefault(); // istanbul ignore else if (focusValue) handleValueChange(focusValue, event.getModifierState("Control") || event.getModifierState("Meta")); // Control or Command return; } else { const [newItemIndex, keyProcessed] = processKeyboardNavigation(optionValues, itemIndex, event.key); // istanbul ignore else if (keyProcessed) { event.preventDefault(); focusOption(newItemIndex); return; } } // istanbul ignore else if (onKeyPress) onKeyPress(event); }, [focusValue, optionValues, focusOption, onKeyPress, handleValueChange]); const isInitialMount = React.useRef(true); React.useEffect(() => { const list = listRef.current as HTMLUListElement; if (isInitialMount.current) { isInitialMount.current = false; if (undefined !== focusValue) { const itemIndex = optionValues.findIndex((optionValue) => (optionValue.value === focusValue)); focusOption(itemIndex); } } else { list.scrollTop = scrollTopRef.current; } }, [focusValue, focusOption, optionValues]); // istanbul ignore next const handleOnScroll = React.useCallback((_event: React.UIEvent<HTMLUListElement, UIEvent>) => { if (listRef.current) scrollTopRef.current = listRef.current.scrollTop; }, []); // istanbul ignore next const handleOnFocus = React.useCallback((_event: React.FocusEvent<HTMLUListElement>) => { if (!focusValue || 0 === focusValue.length) { if (currentValue) { setFocusValue(currentValue); } else { if (optionValues.length > 0) setFocusValue(optionValues[0].value); } } }, [currentValue, focusValue, optionValues]); return <ul className={classes} // If the listbox is not part of another widget, then it has a visible // label referenced by `aria-labelledby` on the element with role // `listbox`. // https://www.w3.org/TR/wai-aria-practices-1.2/#Listbox // If an `aria-label` is passed, we should skip `aria-labelledby` to // avoid confusion. aria-labelledby={ariaLabel ? undefined : ariaLabelledBy} aria-label={ariaLabel} // An element that contains or owns all the listbox options has role // listbox. // https://www.w3.org/TR/wai-aria-practices-1.2/#Listbox role="listbox" // https://www.w3.org/TR/wai-aria-practices-1.2/examples/listbox/listbox-collapsible.html tabIndex={0} // https://www.w3.org/TR/wai-aria-practices-1.2/examples/listbox/listbox-scrollable.html aria-activedescendant={makeId(currentValue, listId)} {...otherProps} ref={listRef} id={listId} onKeyDown={handleKeyDown} onScroll={handleOnScroll} data-value={currentValue} data-focusvalue={focusValue} onFocus={handleOnFocus} > <ListboxContext.Provider value={{ listboxValue: currentValue, focusValue, listboxId: listId, onListboxValueChange: handleValueChange, listboxRef: listRef, }} > {children} </ListboxContext.Provider> </ul>; } /** * `ListboxItem` component. * @alpha */ export function ListboxItem(props: ListboxItemProps) { const { children, value, className, disabled, ...otherProps } = props; const { listboxValue, focusValue, listboxId, onListboxValueChange, } = React.useContext(ListboxContext); const hasFocus = focusValue === value; const classes = React.useMemo(() => classnames("core-listbox-item", hasFocus && "focused", className), [className, hasFocus]); const itemRef = React.useRef<HTMLLIElement>(null); const isSelected = listboxValue === value; const handleClick = React.useCallback((event: React.MouseEvent<HTMLLIElement, MouseEvent>) => { event.preventDefault(); // istanbul ignore next const selectedValue = event.currentTarget?.dataset?.value; // istanbul ignore else if (undefined !== selectedValue) { onListboxValueChange(selectedValue, event.ctrlKey); } }, [onListboxValueChange]); const getItemId = React.useCallback(() => { return makeId(value, listboxId); }, [listboxId, value]); return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events <li // In a single-select listbox, the selected option has `aria-selected` // set to `true`. // https://www.w3.org/TR/wai-aria-practices-1.2/#Listbox aria-selected={isSelected} // Applicable to all host language elements regardless of whether a // `role` is applied. // https://www.w3.org/WAI/PF/aria/states_and_properties#global_states_header aria-disabled={disabled || undefined} // Each option in the listbox has role `option` and is a DOM descendant // of the element with role `listbox`. // https://www.w3.org/TR/wai-aria-practices-1.2/#Listbox role="option" className={classes} {...otherProps} ref={itemRef} id={getItemId()} // used for css styling data-value={value} onClick={handleClick} > {children} </li> ); }
the_stack
import { Request, Response, NextFunction } from "express"; import { InteractionRequiredAuthError, OIDC_DEFAULT_SCOPES, PromptValue } from '@azure/msal-common'; import { ConfidentialClientApplication, Configuration, AccountInfo, ICachePlugin, CryptoProvider, AuthorizationUrlRequest, AuthorizationCodeRequest, } from '@azure/msal-node'; import { ConfigurationUtils } from './ConfigurationUtils'; import { TokenValidator } from './TokenValidator'; import { AppSettings, Resource, AuthCodeParams } from './Types'; import { ErrorMessages } from './Constants'; import * as constants from './Constants'; /** * A simple wrapper around MSAL Node ConfidentialClientApplication object. * It offers a collection of middleware and utility methods that automate * basic authentication and authorization tasks in Express MVC web apps. * * You must have express and express-sessions packages installed. Middleware here * can be used with express sessions in route controllers. * * Session variables accessible are as follows: * req.session.isAuthenticated: boolean * req.session.account: AccountInfo * req.session.<resourceName>.accessToken: string */ export class AuthProvider { appSettings: AppSettings; msalConfig: Configuration; msalClient: ConfidentialClientApplication; private cryptoProvider: CryptoProvider; private tokenValidator: TokenValidator; constructor(appSettings: AppSettings, cache: ICachePlugin = null) { ConfigurationUtils.validateAppSettings(appSettings); this.cryptoProvider = new CryptoProvider(); this.appSettings = appSettings; this.msalConfig = ConfigurationUtils.getMsalConfiguration(appSettings, cache); this.tokenValidator = new TokenValidator(this.appSettings, this.msalConfig); this.msalClient = new ConfidentialClientApplication(this.msalConfig); } // ========== MIDDLEWARE =========== /** * Initiate sign in flow * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next */ signIn = async (req: Request, res: Response, next: NextFunction): Promise<void> => { /** * Request Configuration * We manipulate these two request objects below * to acquire a token with the appropriate claims */ if (!req.session["authCodeRequest"]) { req.session.authCodeRequest = { authority: "", scopes: [], state: {}, redirectUri: "", } as AuthorizationUrlRequest; } if (!req.session["tokenRequest"]) { req.session.tokenRequest = { authority: "", scopes: [], redirectUri: "", code: "", } as AuthorizationCodeRequest; } // signed-in user's account if (!req.session["account"]) { req.session.account = { homeAccountId: "", environment: "", tenantId: "", username: "", idTokenClaims: {}, } as AccountInfo; } // random GUID for csrf check req.session.nonce = this.cryptoProvider.createNewGuid(); /** * The OAuth 2.0 state parameter can be used to encode information of the app's state before redirect. * You can pass the user's state in the app, such as the page or view they were on, as input to this parameter. * MSAL allows you to pass your custom state as state parameter in the request object. For more information, visit: * https://docs.microsoft.com/azure/active-directory/develop/msal-js-pass-custom-state-authentication-request */ const state = this.cryptoProvider.base64Encode( JSON.stringify({ stage: constants.AppStages.SIGN_IN, path: req.route.path, nonce: req.session.nonce }) ); const params: AuthCodeParams = { authority: this.msalConfig.auth.authority, scopes: OIDC_DEFAULT_SCOPES, state: state, redirect: this.appSettings.settings.redirectUri, prompt: PromptValue.SELECT_ACCOUNT, }; // initiate the first leg of auth code grant to get token this.getAuthCode(req, res, next, params); }; /** * Initiate sign out and clean the session * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next */ signOut = async (req: Request, res: Response, next: NextFunction): Promise<any> => { /** * Construct a logout URI and redirect the user to end the * session with Azure AD/B2C. For more information, visit: * (AAD) https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request * (B2C) https://docs.microsoft.com/azure/active-directory-b2c/openid-connect#send-a-sign-out-request */ const logoutURI = `${this.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${this.appSettings.settings.postLogoutRedirectUri}`; req.session.isAuthenticated = false; req.session.destroy(() => { res.redirect(logoutURI); }); } /** * Middleware that handles redirect depending on request state * There are basically 2 stages: sign-in and acquire token * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next */ handleRedirect = async (req: Request, res: Response, next: NextFunction): Promise<any> => { if (req.query.state) { const state = JSON.parse(this.cryptoProvider.base64Decode(req.query.state as string)); // check if nonce matches if (state.nonce === req.session.nonce) { switch (state.stage) { case constants.AppStages.SIGN_IN: { // token request should have auth code req.session.tokenRequest.code = req.query.code as string; try { // exchange auth code for tokens const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest) console.log("\nResponse: \n:", tokenResponse); try { const isIdTokenValid = await this.tokenValidator.validateIdToken(tokenResponse.idToken); if (isIdTokenValid) { // assign session variables req.session.account = tokenResponse.account; req.session.isAuthenticated = true; return res.status(200).redirect(this.appSettings.settings.homePageRoute); } else { console.log(ErrorMessages.INVALID_TOKEN); return res.status(401).send(ErrorMessages.NOT_PERMITTED); } } catch (error) { console.log(error); next(error); } } catch (error) { console.log(error); next(error); } break; } case constants.AppStages.ACQUIRE_TOKEN: { // get the name of the resource associated with scope const resourceName = this.getResourceName(state.path); req.session.tokenRequest.code = req.query.code as string try { const tokenResponse = await this.msalClient.acquireTokenByCode(req.session.tokenRequest); console.log("\nResponse: \n:", tokenResponse); req.session[resourceName].accessToken = tokenResponse.accessToken; return res.status(200).redirect(state.path); } catch (error) { console.log(error); next(error); } break; } default: res.status(500).send(ErrorMessages.CANNOT_DETERMINE_APP_STAGE); break; } } else { console.log(ErrorMessages.NONCE_MISMATCH) res.status(401).send(ErrorMessages.NOT_PERMITTED); } } else { console.log(ErrorMessages.STATE_NOT_FOUND) res.status(401).send(ErrorMessages.NOT_PERMITTED); } }; /** * Middleware that gets tokens and calls web APIs * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next */ getToken = async (req: Request, res: Response, next: NextFunction): Promise<void> => { // get scopes for token request const scopes = (<Resource>Object.values(this.appSettings.resources) .find((resource: Resource) => resource.callingPageRoute === req.route.path)).scopes; const resourceName = this.getResourceName(req.route.path); if (!req.session[resourceName]) { req.session[resourceName] = { accessToken: null, }; } try { const tokenCache = await this.msalClient.getTokenCache(); const account = await tokenCache.getAccountByHomeId(req.session.account.homeAccountId); const silentRequest = { account: account, scopes: scopes, }; // acquire token silently to be used in resource call const tokenResponse = await this.msalClient.acquireTokenSilent(silentRequest) console.log("\nSuccessful silent token acquisition:\n Response: \n:", tokenResponse); // In B2C scenarios, sometimes an access token is returned empty. // In that case, we will acquire token interactively instead. if (tokenResponse.accessToken.length === 0) { console.log(ErrorMessages.TOKEN_NOT_FOUND); throw new InteractionRequiredAuthError(ErrorMessages.INTERACTION_REQUIRED); } req.session[resourceName].accessToken = tokenResponse.accessToken; next(); } catch (error) { // in case there are no cached tokens, initiate an interactive call if (error instanceof InteractionRequiredAuthError) { const state = this.cryptoProvider.base64Encode( JSON.stringify({ stage: constants.AppStages.ACQUIRE_TOKEN, path: req.route.path, nonce: req.session.nonce }) ); const params: AuthCodeParams = { authority: this.msalConfig.auth.authority, scopes: scopes, state: state, redirect: this.appSettings.settings.redirectUri, account: req.session.account, }; // initiate the first leg of auth code grant to get token this.getAuthCode(req, res, next, params); } else { next(error); } } } // ============== GUARD =============== /** * Check if authenticated in session * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next */ isAuthenticated = (req: Request, res: Response, next: NextFunction): Response | void => { if (req.session) { if (!req.session.isAuthenticated) { return res.status(401).send(ErrorMessages.NOT_PERMITTED); } next(); } else { res.status(401).send(ErrorMessages.NOT_PERMITTED); } } // ============== UTILS =============== /** * This method is used to generate an auth code request * @param {Request} req: express request object * @param {Response} res: express response object * @param {NextFunction} next: express next * @param {AuthCodeParams} params: modify auth code url request */ private getAuthCode = async (req: Request, res: Response, next: NextFunction, params: AuthCodeParams): Promise<void> => { // prepare the request req.session.authCodeRequest.authority = params.authority; req.session.authCodeRequest.scopes = params.scopes; req.session.authCodeRequest.state = params.state; req.session.authCodeRequest.redirectUri = params.redirect; req.session.tokenRequest.authority = params.authority; req.session.tokenRequest.redirectUri = params.redirect; req.session.tokenRequest.scopes = params.scopes; // request an authorization code to exchange for tokens try { const response = await this.msalClient.getAuthCodeUrl(req.session.authCodeRequest); res.redirect(response); } catch (error) { console.log(JSON.stringify(error)); next(error); } } /** * Util method to get the resource name for a given callingPageRoute (appSettings.json) * @param {string} path: route path */ private getResourceName = (path: string): string => { const index = Object.values(this.appSettings.resources).findIndex((resource: Resource) => resource.callingPageRoute === path); const resourceName = Object.keys(this.appSettings.resources)[index]; return resourceName; } }
the_stack
import { code as ctWrapperScript } from 'code ./browser/contentScriptWrapper.ts' import { cosmiconfigSync } from 'cosmiconfig' import fs from 'fs-extra' import { JSONPath } from 'jsonpath-plus' import memoize from 'mem' import path, { basename, relative } from 'path' import { EmittedAsset, OutputChunk } from 'rollup' import slash from 'slash' import { isChunk, isPresent, normalizeFilename, } from '../helpers' import { isMV2, isMV3 } from '../manifest-types' import { ManifestInputPlugin, ManifestInputPluginCache, ManifestInputPluginOptions, } from '../plugin-options' import { cloneObject } from './cloneObject' import { prepImportWrapperScript } from './dynamicImportWrapper' import { getInputManifestPath } from './getInputManifestPath' import { combinePerms } from './manifest-parser/combine' import { deriveFiles, derivePermissions, } from './manifest-parser/index' import { validateManifest } from './manifest-parser/validate' import { reduceToRecord } from './reduceToRecord' import { getImportContentScriptFileName, updateManifestV3, } from './updateManifest' import { warnDeprecatedOptions } from './warnDeprecatedOptions' export const explorer = cosmiconfigSync('manifest', { cache: false, loaders: { '.ts': (filePath: string) => { require('esbuild-runner/register') const result = require(filePath) return result.default ?? result }, }, }) const name = 'manifest-input' // We use a stub if the manifest has no scripts // eg, a CSS only Chrome Extension export const stubChunkNameForCssOnlyCrx = 'stub__css-only-chrome-extension-manifest' export const importWrapperChunkNamePrefix = '__RPCE-import-wrapper' const npmPkgDetails = process.env.npm_package_name && process.env.npm_package_version && process.env.npm_package_description ? { name: process.env.npm_package_name, version: process.env.npm_package_version, description: process.env.npm_package_description, } : { name: '', version: '', description: '', } /* ============================================ */ /* MANIFEST-INPUT */ /* ============================================ */ export function manifestInput( { browserPolyfill = false, contentScriptWrapper = true, crossBrowser = false, dynamicImportWrapper = {}, extendManifest = {}, firstClassManifest = true, iifeJsonPaths = [], pkg = npmPkgDetails, publicKey, verbose = true, wrapContentScripts = true, cache = { assetChanged: false, assets: [], contentScripts: [], contentScriptCode: {}, contentScriptIds: {}, iife: [], input: [], inputAry: [], inputObj: {}, permsHash: '', readFile: new Map<string, any>(), srcDir: null, } as ManifestInputPluginCache, } = {} as ManifestInputPluginOptions, ): ManifestInputPlugin { const readAssetAsBuffer = memoize( (filepath: string) => { return fs.readFile(filepath) }, { cache: cache.readFile, }, ) /* ------------------ DEPRECATIONS ----------------- */ // contentScriptWrapper = wrapContentScripts /* ----------- HOOKS CLOSURES START ----------- */ let manifestPath: string const manifestName = 'manifest.json' /* ------------ HOOKS CLOSURES END ------------ */ /* - SETUP DYNAMIC IMPORT LOADER SCRIPT START - */ let wrapperScript = '' if (dynamicImportWrapper !== false) { wrapperScript = prepImportWrapperScript(dynamicImportWrapper) } /* -- SETUP DYNAMIC IMPORT LOADER SCRIPT END -- */ /* --------------- plugin object -------------- */ return { name, browserPolyfill, crossBrowser, get srcDir() { return cache.srcDir }, get formatMap() { return { iife: cache.iife } }, /* ============================================ */ /* OPTIONS HOOK */ /* ============================================ */ options(options) { /* ----------- LOAD AND PROCESS MANIFEST ----------- */ // Do not reload manifest without changes if (!cache.manifest) { const { inputManifestPath, ...cacheValues } = getInputManifestPath(options) Object.assign(cache, cacheValues) const configResult = explorer.load( inputManifestPath, ) as { filepath: string config: chrome.runtime.Manifest isEmpty?: true } if (configResult.isEmpty) { throw new Error(`${options.input} is an empty file.`) } const { options_page, options_ui } = configResult.config if (isPresent(options_ui) && isPresent(options_page)) { throw new Error( 'options_ui and options_page cannot both be defined in manifest.json.', ) } manifestPath = configResult.filepath cache.srcDir = path.dirname(manifestPath) let extendedManifest: Partial<chrome.runtime.Manifest> if (typeof extendManifest === 'function') { extendedManifest = extendManifest(configResult.config) } else if (typeof extendManifest === 'object') { extendedManifest = { ...configResult.config, ...extendManifest, } as Partial<chrome.runtime.Manifest> } else { extendedManifest = configResult.config } const fullManifest = { // MV2 is default manifest_version: 2, name: pkg.name, // version must be all digits with up to three dots version: [ ...(pkg.version?.matchAll(/\d+/g) ?? []), ].join('.'), description: pkg.description, ...extendedManifest, } as chrome.runtime.Manifest // If the manifest is the source of truth for inputs // `false` means that all inputs must come from Rollup config if (firstClassManifest) { // Any scripts from here will be regenerated as IIFE's cache.iife = iifeJsonPaths .map((jsonPath) => { const result = JSONPath({ path: jsonPath, json: fullManifest, }) return result }) .flat(Infinity) // Derive entry paths from manifest const { js, html, css, img, others, contentScripts, } = deriveFiles(fullManifest, cache.srcDir, { contentScripts: true, }) cache.contentScripts = contentScripts // Cache derived inputs cache.input = [...cache.inputAry, ...js, ...html] cache.assets = [ // Dedupe assets ...new Set([...css, ...img, ...others]), ] } let finalManifest: chrome.runtime.Manifest if (isMV3(fullManifest)) { finalManifest = updateManifestV3( fullManifest, options, cache, ) } else { finalManifest = fullManifest } cache.manifest = validateManifest(finalManifest) } /* --------------- END LOAD MANIFEST --------------- */ // Final `options.input` is an object // this grants full compatibility with all Rollup options const finalInput = cache.input.reduce( reduceToRecord(cache.srcDir), cache.inputObj, ) // Use a stub if no js scripts if (Object.keys(finalInput).length === 0) { finalInput[ stubChunkNameForCssOnlyCrx ] = stubChunkNameForCssOnlyCrx } return { ...options, input: finalInput } }, async buildStart() { /* ------------ WATCH ASSETS FOR CHANGES ----------- */ this.addWatchFile(manifestPath) cache.assets.forEach((srcPath) => { this.addWatchFile(srcPath) }) /* ------------------ EMIT ASSETS ------------------ */ const assets: EmittedAsset[] = await Promise.all( cache.assets.map(async (srcPath) => { const source = await readAssetAsBuffer(srcPath) return { type: 'asset' as const, source, fileName: path.relative(cache.srcDir!, srcPath), } }), ) assets.forEach((asset) => { this.emitFile(asset) }) warnDeprecatedOptions.call( this, { browserPolyfill, crossBrowser, dynamicImportWrapper, firstClassManifest, iifeJsonPaths, publicKey, }, cache, ) // MV2 manifest is handled in `generateBundle` if (isMV2(cache.manifest)) return /* ---------- EMIT CONTENT SCRIPT WRAPPERS --------- */ /* --------------- EMIT MV3 MANIFEST --------------- */ const manifestBody = cloneObject(cache.manifest!) const manifestJson = JSON.stringify( manifestBody, undefined, 2, ).replace(/\.[jt]sx?"/g, '.js"') // Emit manifest.json this.emitFile({ type: 'asset', fileName: manifestName, source: manifestJson, }) }, async resolveId(source) { return source === stubChunkNameForCssOnlyCrx || source.startsWith(importWrapperChunkNamePrefix) ? source : null }, load(id) { if (id === stubChunkNameForCssOnlyCrx) { return { code: `console.log(${stubChunkNameForCssOnlyCrx})`, } } else if ( wrapContentScripts && isMV3(cache.manifest) && id.startsWith(importWrapperChunkNamePrefix) ) { const [, target] = id.split(':') const code = ctWrapperScript.replace( '%PATH%', JSON.stringify(target), ) return { code } } return null }, transform(code, id) { if ( wrapContentScripts && isMV3(cache.manifest) && cache.contentScripts.includes(id) ) { // Use slash to guarantee support Windows const target = `${slash(relative(cache.srcDir!, id)) .split('.') .slice(0, -1) .join('.')}.js` const fileName = getImportContentScriptFileName(target) // Emit content script wrapper this.emitFile({ id: `${importWrapperChunkNamePrefix}:${target}`, type: 'chunk', fileName, }) } // No source transformation took place return { code, map: null } }, watchChange(id) { if (id.endsWith(manifestName)) { // Dump cache.manifest if manifest changes delete cache.manifest cache.assetChanged = false } else { // Force new read of changed asset cache.assetChanged = cache.readFile.delete(id) } }, /* ============================================ */ /* GENERATEBUNDLE */ /* ============================================ */ generateBundle(options, bundle) { /* ----------------- CLEAN UP STUB ----------------- */ delete bundle[stubChunkNameForCssOnlyCrx + '.js'] // We don't support completely empty bundles if (Object.keys(bundle).length === 0) { throw new Error( 'The Chrome extension must have at least one asset (html or css) or script file.', ) } // MV3 is handled in `buildStart` to support Vite if (isMV3(cache.manifest)) return /* ------------------------------------------------- */ /* EMIT MV2 MANIFEST */ /* ------------------------------------------------- */ /* ------------ DERIVE PERMISSIONS START ----------- */ let permissions: string[] = [] // Get module ids for all chunks if (cache.assetChanged && cache.permsHash) { // Permissions did not change permissions = JSON.parse(cache.permsHash) as string[] cache.assetChanged = false } else { const chunks = Object.values(bundle).filter(isChunk) // Permissions may have changed permissions = Array.from( chunks.reduce(derivePermissions, new Set<string>()), ) const permsHash = JSON.stringify(permissions) if (verbose && permissions.length) { if (!cache.permsHash) { this.warn( `Detected permissions: ${permissions.toString()}`, ) } else if (permsHash !== cache.permsHash) { this.warn( `Detected new permissions: ${permissions.toString()}`, ) } } cache.permsHash = permsHash } const clonedManifest = cloneObject( cache.manifest, ) as chrome.runtime.ManifestV2 const manifestBody = { ...clonedManifest, permissions: combinePerms( permissions, clonedManifest.permissions || [], ), } const { background: { scripts: bgs = [] } = {}, content_scripts: cts = [], web_accessible_resources: war = [], } = manifestBody /* ------------ SETUP BACKGROUND SCRIPTS ----------- */ // Emit background script wrappers if (bgs.length && wrapperScript.length) { // background exists because bgs has scripts manifestBody.background!.scripts = bgs .map(normalizeFilename) .map((scriptPath: string) => { // Loader script exists because of type guard above const source = // Path to module being loaded wrapperScript.replace( '%PATH%', // Fix path slashes to support Windows JSON.stringify( slash(relative('assets', scriptPath)), ), ) const assetId = this.emitFile({ type: 'asset', source, name: basename(scriptPath), }) return this.getFileName(assetId) }) .map((p) => slash(p)) } /* ---------- END SETUP BACKGROUND SCRIPTS --------- */ /* ------------- SETUP CONTENT SCRIPTS ------------- */ const contentScripts = cts.reduce( (r, { js = [] }) => [...r, ...js], [] as string[], ) if (contentScriptWrapper && contentScripts.length) { const memoizedEmitter = memoize((scriptPath: string) => { const source = ctWrapperScript.replace( '%PATH%', // Fix path slashes to support Windows JSON.stringify( slash(relative('assets', scriptPath)), ), ) const assetId = this.emitFile({ type: 'asset', source, name: basename(scriptPath), }) return this.getFileName(assetId) }) // Setup content script import wrapper manifestBody.content_scripts = cts.map( ({ js, ...rest }) => { return typeof js === 'undefined' ? rest : { js: js .map(normalizeFilename) .map(memoizedEmitter) .map((p) => slash(p)), ...rest, } }, ) // make all imports & dynamic imports web_acc_res const imports = Object.values(bundle) .filter((x): x is OutputChunk => x.type === 'chunk') .reduce( (r, { isEntry, fileName }) => // Get imported filenames !isEntry ? [...r, fileName] : r, [] as string[], ) manifestBody.web_accessible_resources = Array.from( new Set([ ...war, // FEATURE: filter out imports for background? ...imports, // Need to be web accessible b/c of import ...contentScripts, ]), ).map((p) => slash(p)) /* ----------- END SETUP CONTENT SCRIPTS ----------- */ } /* --------- STABLE EXTENSION ID BEGIN -------- */ if (publicKey) { manifestBody.key = publicKey } /* ---------- STABLE EXTENSION ID END --------- */ /* ----------- OUTPUT MANIFEST.JSON BEGIN ---------- */ const manifestJson = JSON.stringify( manifestBody, null, 2, ).replace(/\.[jt]sx?"/g, '.js"') // Emit manifest.json this.emitFile({ type: 'asset', fileName: manifestName, source: manifestJson, }) /* ------------ OUTPUT MANIFEST.JSON END ----------- */ }, } } export default manifestInput
the_stack
import { stub, SinonStub, useFakeTimers, SinonFakeTimers } from 'sinon'; import { Trace } from '../resources/trace'; import * as transportService from './transport_service'; import * as iidService from './iid_service'; import { expect } from 'chai'; import { Api, setupApi } from './api_service'; import { SettingsService } from './settings_service'; import { FirebaseApp } from '@firebase/app'; import * as initializationService from './initialization_service'; import { SDK_VERSION } from '../constants'; import * as attributeUtils from '../utils/attributes_utils'; import { createNetworkRequestEntry } from '../resources/network_request'; import '../../test/setup'; import { mergeStrings } from '../utils/string_merger'; import { FirebaseInstallations } from '@firebase/installations-types'; import { PerformanceController } from '../controllers/perf'; describe('Performance Monitoring > perf_logger', () => { const IID = 'idasdfsffe'; const PAGE_URL = 'http://mock-page.com'; const APP_ID = '1:123:web:2er'; const VISIBILITY_STATE = 3; const EFFECTIVE_CONNECTION_TYPE = 2; const SERVICE_WORKER_STATUS = 3; const TIME_ORIGIN = 1556512199893.9033; const TRACE_NAME = 'testTrace'; const START_TIME = 12345; const DURATION = 321; // Perf event header which is constant across tests in this file. const WEBAPP_INFO = `"application_info":{"google_app_id":"${APP_ID}",\ "app_instance_id":"${IID}","web_app_info":{"sdk_version":"${SDK_VERSION}",\ "page_url":"${PAGE_URL}","service_worker_status":${SERVICE_WORKER_STATUS},\ "visibility_state":${VISIBILITY_STATE},"effective_connection_type":${EFFECTIVE_CONNECTION_TYPE}},\ "application_process_state":0}`; let addToQueueStub: SinonStub< Array<{ message: string; eventTime: number }>, void >; let getIidStub: SinonStub<[], string | undefined>; let clock: SinonFakeTimers; function mockTransportHandler( serializer: (...args: any[]) => string ): (...args: any[]) => void { return (...args) => { const message = serializer(...args); addToQueueStub({ message, eventTime: Date.now() }); }; } setupApi(self); const fakeFirebaseApp = { options: { appId: APP_ID } } as unknown as FirebaseApp; const fakeInstallations = {} as unknown as FirebaseInstallations; const performanceController = new PerformanceController( fakeFirebaseApp, fakeInstallations ); beforeEach(() => { getIidStub = stub(iidService, 'getIid'); addToQueueStub = stub(); stub(transportService, 'transportHandler').callsFake(mockTransportHandler); stub(Api.prototype, 'getUrl').returns(PAGE_URL); stub(Api.prototype, 'getTimeOrigin').returns(TIME_ORIGIN); stub(attributeUtils, 'getEffectiveConnectionType').returns( EFFECTIVE_CONNECTION_TYPE ); stub(attributeUtils, 'getServiceWorkerStatus').returns( SERVICE_WORKER_STATUS ); clock = useFakeTimers(); }); describe('logTrace', () => { it('will not drop custom events sent before initialization finishes', async () => { getIidStub.returns(IID); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); stub(initializationService, 'isPerfInitialized').returns(false); // Simulates logging being enabled after initialization completes. const initializationPromise = Promise.resolve().then(() => { SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logTraceAfterSampling = true; }); stub(initializationService, 'getInitializationPromise').returns( initializationPromise ); const trace = new Trace(performanceController, TRACE_NAME); trace.record(START_TIME, DURATION); await initializationPromise.then(() => { clock.tick(1); }); expect(addToQueueStub).to.be.called; }); it('creates, serializes and sends a trace to transport service', () => { const EXPECTED_TRACE_MESSAGE = `{` + WEBAPP_INFO + `,"trace_metric":{"name":"${TRACE_NAME}","is_auto":false,\ "client_start_time_us":${START_TIME * 1000},"duration_us":${DURATION * 1000},\ "counters":{"counter1":3},"custom_attributes":{"attr":"val"}}}`; getIidStub.returns(IID); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); stub(initializationService, 'isPerfInitialized').returns(true); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logTraceAfterSampling = true; const trace = new Trace(performanceController, TRACE_NAME); trace.putAttribute('attr', 'val'); trace.putMetric('counter1', 3); trace.record(START_TIME, DURATION); clock.tick(1); expect(addToQueueStub).to.be.called; expect(addToQueueStub.getCall(0).args[0].message).to.be.equal( EXPECTED_TRACE_MESSAGE ); }); it('does not log an event if cookies are disabled in the browser', () => { stub(Api.prototype, 'requiredApisAvailable').returns(false); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); stub(initializationService, 'isPerfInitialized').returns(true); const trace = new Trace(performanceController, TRACE_NAME); trace.record(START_TIME, DURATION); clock.tick(1); expect(addToQueueStub).not.to.be.called; }); it('ascertains that the max number of customMetric allowed is 32', () => { const EXPECTED_TRACE_MESSAGE = `{` + WEBAPP_INFO + `,"trace_metric":{"name":"${TRACE_NAME}","is_auto":false,\ "client_start_time_us":${START_TIME * 1000},"duration_us":${DURATION * 1000},\ "counters":{"counter1":1,"counter2":2,"counter3":3,"counter4":4,"counter5":5,"counter6":6,\ "counter7":7,"counter8":8,"counter9":9,"counter10":10,"counter11":11,"counter12":12,\ "counter13":13,"counter14":14,"counter15":15,"counter16":16,"counter17":17,"counter18":18,\ "counter19":19,"counter20":20,"counter21":21,"counter22":22,"counter23":23,"counter24":24,\ "counter25":25,"counter26":26,"counter27":27,"counter28":28,"counter29":29,"counter30":30,\ "counter31":31,"counter32":32}}}`; getIidStub.returns(IID); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); stub(initializationService, 'isPerfInitialized').returns(true); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logTraceAfterSampling = true; const trace = new Trace(performanceController, TRACE_NAME); for (let i = 1; i <= 32; i++) { trace.putMetric('counter' + i, i); } trace.record(START_TIME, DURATION); clock.tick(1); expect(addToQueueStub).to.be.called; expect(addToQueueStub.getCall(0).args[0].message).to.be.equal( EXPECTED_TRACE_MESSAGE ); }); it('ascertains that the max number of custom attributes allowed is 5', () => { const EXPECTED_TRACE_MESSAGE = `{` + WEBAPP_INFO + `,"trace_metric":{"name":"${TRACE_NAME}","is_auto":false,\ "client_start_time_us":${START_TIME * 1000},"duration_us":${DURATION * 1000},\ "custom_attributes":{"attr1":"val1","attr2":"val2","attr3":"val3","attr4":"val4","attr5":"val5"}}}`; getIidStub.returns(IID); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); stub(initializationService, 'isPerfInitialized').returns(true); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logTraceAfterSampling = true; const trace = new Trace(performanceController, TRACE_NAME); for (let i = 1; i <= 5; i++) { trace.putAttribute('attr' + i, 'val' + i); } trace.record(START_TIME, DURATION); clock.tick(1); expect(addToQueueStub).to.be.called; expect(addToQueueStub.getCall(0).args[0].message).to.be.equal( EXPECTED_TRACE_MESSAGE ); }); }); describe('logPageLoadTrace', () => { it('creates, serializes and sends a page load trace to cc service', () => { const flooredStartTime = Math.floor(TIME_ORIGIN * 1000); const EXPECTED_TRACE_MESSAGE = `{"application_info":{"google_app_id":"${APP_ID}",\ "app_instance_id":"${IID}","web_app_info":{"sdk_version":"${SDK_VERSION}",\ "page_url":"${PAGE_URL}","service_worker_status":${SERVICE_WORKER_STATUS},\ "visibility_state":${ attributeUtils.VisibilityState.VISIBLE },"effective_connection_type":${EFFECTIVE_CONNECTION_TYPE}},\ "application_process_state":0},"trace_metric":{"name":"_wt_${PAGE_URL}","is_auto":true,\ "client_start_time_us":${flooredStartTime},"duration_us":${DURATION * 1000},\ "counters":{"domInteractive":10000,"domContentLoadedEventEnd":20000,"loadEventEnd":10000,\ "_fp":40000,"_fcp":50000,"_fid":90000}}}`; stub(initializationService, 'isPerfInitialized').returns(true); getIidStub.returns(IID); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logTraceAfterSampling = true; stub(attributeUtils, 'getVisibilityState').returns( attributeUtils.VisibilityState.VISIBLE ); const navigationTiming: PerformanceNavigationTiming = { domComplete: 100, domContentLoadedEventEnd: 20, domContentLoadedEventStart: 10, domInteractive: 10, loadEventEnd: 10, loadEventStart: 10, redirectCount: 10, type: 'navigate', unloadEventEnd: 10, unloadEventStart: 10, duration: DURATION } as PerformanceNavigationTiming; const navigationTimings: PerformanceNavigationTiming[] = [ navigationTiming ]; const firstPaint: PerformanceEntry = { name: 'first-paint', startTime: 40, duration: 100, entryType: 'url', toJSON() {} }; const firstContentfulPaint: PerformanceEntry = { name: 'first-contentful-paint', startTime: 50, duration: 100, entryType: 'url', toJSON() {} }; const paintTimings: PerformanceEntry[] = [ firstPaint, firstContentfulPaint ]; Trace.createOobTrace( performanceController, navigationTimings, paintTimings, 90 ); clock.tick(1); expect(addToQueueStub).to.be.called; expect(addToQueueStub.getCall(0).args[0].message).to.be.equal( EXPECTED_TRACE_MESSAGE ); }); }); describe('logNetworkRequest', () => { it('creates, serializes and sends a network request to transport service', () => { const RESOURCE_PERFORMANCE_ENTRY: PerformanceResourceTiming = { connectEnd: 0, connectStart: 0, decodedBodySize: 0, domainLookupEnd: 0, domainLookupStart: 0, duration: 39.610000094398856, encodedBodySize: 0, entryType: 'resource', fetchStart: 5645.689999917522, initiatorType: 'fetch', name: 'https://test.com/abc', nextHopProtocol: 'http/2+quic/43', redirectEnd: 0, redirectStart: 0, requestStart: 0, responseEnd: 5685.300000011921, responseStart: 0, secureConnectionStart: 0, startTime: 5645.689999917522, transferSize: 0, workerStart: 0, toJSON: () => {} }; const START_TIME = Math.floor( (TIME_ORIGIN + RESOURCE_PERFORMANCE_ENTRY.startTime) * 1000 ); const TIME_TO_RESPONSE_COMPLETED = Math.floor( (RESOURCE_PERFORMANCE_ENTRY.responseEnd - RESOURCE_PERFORMANCE_ENTRY.startTime) * 1000 ); const EXPECTED_NETWORK_MESSAGE = `{` + WEBAPP_INFO + `,\ "network_request_metric":{"url":"${RESOURCE_PERFORMANCE_ENTRY.name}",\ "http_method":0,"http_response_code":200,\ "response_payload_bytes":${RESOURCE_PERFORMANCE_ENTRY.transferSize},\ "client_start_time_us":${START_TIME},\ "time_to_response_completed_us":${TIME_TO_RESPONSE_COMPLETED}}}`; stub(initializationService, 'isPerfInitialized').returns(true); getIidStub.returns(IID); stub(attributeUtils, 'getVisibilityState').returns(VISIBILITY_STATE); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logNetworkAfterSampling = true; // Calls logNetworkRequest under the hood. createNetworkRequestEntry( performanceController, RESOURCE_PERFORMANCE_ENTRY ); clock.tick(1); expect(addToQueueStub).to.be.called; expect(addToQueueStub.getCall(0).args[0].message).to.be.equal( EXPECTED_NETWORK_MESSAGE ); }); // Performance SDK doesn't instrument requests sent from SDK itself, therefore blacklist // requests sent to cc endpoint. it('skips performance collection if domain is cc', () => { const CC_NETWORK_PERFORMANCE_ENTRY: PerformanceResourceTiming = { connectEnd: 0, connectStart: 0, decodedBodySize: 0, domainLookupEnd: 0, domainLookupStart: 0, duration: 39.610000094398856, encodedBodySize: 0, entryType: 'resource', fetchStart: 5645.689999917522, initiatorType: 'fetch', name: 'https://firebaselogging.googleapis.com/v0cc/log?message=a', nextHopProtocol: 'http/2+quic/43', redirectEnd: 0, redirectStart: 0, requestStart: 0, responseEnd: 5685.300000011921, responseStart: 0, secureConnectionStart: 0, startTime: 5645.689999917522, transferSize: 0, workerStart: 0, toJSON: () => {} }; stub(initializationService, 'isPerfInitialized').returns(true); getIidStub.returns(IID); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logNetworkAfterSampling = true; // Calls logNetworkRequest under the hood. createNetworkRequestEntry( performanceController, CC_NETWORK_PERFORMANCE_ENTRY ); clock.tick(1); expect(addToQueueStub).not.called; }); // Performance SDK doesn't instrument requests sent from SDK itself, therefore blacklist // requests sent to fl endpoint. it('skips performance collection if domain is fl', () => { const FL_NETWORK_PERFORMANCE_ENTRY: PerformanceResourceTiming = { connectEnd: 0, connectStart: 0, decodedBodySize: 0, domainLookupEnd: 0, domainLookupStart: 0, duration: 39.610000094398856, encodedBodySize: 0, entryType: 'resource', fetchStart: 5645.689999917522, initiatorType: 'fetch', name: mergeStrings( 'hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o' ), nextHopProtocol: 'http/2+quic/43', redirectEnd: 0, redirectStart: 0, requestStart: 0, responseEnd: 5685.300000011921, responseStart: 0, secureConnectionStart: 0, startTime: 5645.689999917522, transferSize: 0, workerStart: 0, toJSON: () => {} }; stub(initializationService, 'isPerfInitialized').returns(true); getIidStub.returns(IID); SettingsService.getInstance().loggingEnabled = true; SettingsService.getInstance().logNetworkAfterSampling = true; // Calls logNetworkRequest under the hood. createNetworkRequestEntry( performanceController, FL_NETWORK_PERFORMANCE_ENTRY ); clock.tick(1); expect(addToQueueStub).not.called; }); }); });
the_stack
import { Theme } from './theme'; export const devuiLightTheme: Theme = new Theme({ id: 'devui-light-theme', name: 'Light Mode', cnName: '浅色主题', data: { // 基础变量 'devui-global-bg': '#f3f6f8', 'devui-global-bg-normal': '#ffffff', 'devui-base-bg': '#ffffff', 'devui-base-bg-dark': '#333854', 'devui-brand': '#5e7ce0', 'devui-brand-foil': '#859bff', 'devui-brand-hover': '#7693f5', 'devui-brand-active': '#526ecc', 'devui-brand-active-focus': '#344899', 'devui-contrast': '#c7000b', 'devui-text': '#252b3a', 'devui-text-weak': '#575d6c', 'devui-aide-text': '#8a8e99', 'devui-aide-text-stress': '#575d6c', 'devui-placeholder': '#8a8e99', 'devui-light-text': '#ffffff', 'devui-dark-text': '#252b3a', 'devui-link': '#526ecc', 'devui-link-active': '#526ecc', 'devui-link-light': '#96adfa', 'devui-link-light-active': '#beccfa', 'devui-line': '#adb0b8', 'devui-dividing-line': '#dfe1e6', 'devui-block': '#ffffff', 'devui-area': '#f8f8f8', 'devui-danger': '#f66f6a', 'devui-warning': '#fac20a', 'devui-waiting': '#9faad7', 'devui-success': '#50d4ab', 'devui-info': '#5e7ce0', 'devui-initial': '#e9edfa', 'devui-unavailable': '#f5f5f6', 'devui-shadow': 'rgba(0, 0, 0, 0.2)', 'devui-light-shadow': 'rgba(0, 0, 0, 0.1)', // 图标 'devui-icon-text': '#252b3a', 'devui-icon-bg': '#ffffff', 'devui-icon-fill': '#d3d5d9', 'devui-icon-fill-hover': '#adb5ce', 'devui-icon-fill-active': '#5e7ce0', 'devui-icon-fill-active-hover': '#526ecc', // 表单 'devui-form-control-line': '#adb0b8', 'devui-form-control-line-hover': '#575d6c', 'devui-form-control-line-active': '#5e7ce0', 'devui-form-control-line-active-hover': '#344899', 'devui-list-item-active-bg': '#5e7ce0', 'devui-list-item-active-text': '#ffffff', 'devui-list-item-active-hover-bg': '#526ecc', 'devui-list-item-hover-bg': '#f2f5fc', 'devui-list-item-hover-text': '#526ecc', 'devui-list-item-selected-bg': '#e9edfa', 'devui-list-item-strip-bg': '#f2f5fc', // 禁用 'devui-disabled-bg': '#f5f5f6', 'devui-disabled-line': '#dfe1e6', 'devui-disabled-text': '#adb0b8', 'devui-primary-disabled': '#beccfa', 'devui-icon-fill-active-disabled': '#beccfa', // 特殊背景色 'devui-label-bg': '#eef0f5', 'devui-connected-overlay-bg': '#ffffff', 'devui-connected-overlay-line': '#526ecc', 'devui-fullscreen-overlay-bg': '#ffffff', 'devui-feedback-overlay-bg': '#464d6e', 'devui-feedback-overlay-text': '#dfe1e6', 'devui-embed-search-bg': '#f2f5fc', 'devui-embed-search-bg-hover': '#eef0f5', 'devui-float-block-shadow': 'rgba(94, 124, 224, 0.3)', 'devui-highlight-overlay': 'rgba(255, 255, 255, 0.8)', 'devui-range-item-hover-bg': '#e9edfa', // 按钮 'devui-primary': '#5e7ce0', 'devui-primary-hover': '#7693f5', 'devui-primary-active': '#344899', 'devui-contrast-hover': '#d64a52', 'devui-contrast-active': '#b12220', // 状态 'devui-danger-line': '#f66f6a', 'devui-danger-bg': '#ffeeed', 'devui-warning-line': '#fa9841', 'devui-warning-bg': '#fff3e8', 'devui-info-line': '#5e7ce0', 'devui-info-bg': '#f2f5fc', 'devui-success-line': '#50d4ab', 'devui-success-bg': '#edfff9', 'devui-primary-line': '#5e7ce0', 'devui-primary-bg': '#f2f5fc', 'devui-default-line': '#5e7ce0', 'devui-default-bg': '#f3f6f8', // 字体设置相关 'devui-font-size': '12px', 'devui-font-size-card-title': '14px', 'devui-font-size-page-title': '16px', 'devui-font-size-modal-title': '18px', 'devui-font-size-price': '20px', 'devui-font-size-data-overview': '24px', 'devui-font-size-icon': '16px', 'devui-font-size-sm': '12px', 'devui-font-size-md': '12px', 'devui-font-size-lg': '14px', 'devui-font-title-weight': 'bold', 'devui-font-content-weight': 'normal', 'devui-line-height-base': '1.5', // 圆角 'devui-border-radius': '2px', 'devui-border-radius-feedback': '4px', 'devui-border-radius-card': '6px', // 阴影 'devui-shadow-length-base': '0 1px 4px 0', 'devui-shadow-length-slide-left': '-2px 0 8px 0', 'devui-shadow-length-slide-right': '2px 0 8px 0', 'devui-shadow-length-connected-overlay': '0 2px 8px 0', 'devui-shadow-length-hover': '0 4px 16px 0', 'devui-shadow-length-feedback-overlay': '0 4px 16px 0', 'devui-shadow-fullscreen-overlay': '0 8px 40px 0', // 动效 'devui-animation-duration-slow': '300ms', 'devui-animation-duration-base': '200ms', 'devui-animation-duration-fast': '100ms', 'devui-animation-ease-in': 'cubic-bezier(0.5, 0, 0.84, 0.25)', 'devui-animation-ease-out': 'cubic-bezier(0.16, 0.75, 0.5, 1)', 'devui-animation-ease-in-out': 'cubic-bezier(0.5, 0.05, 0.5, 0.95)', 'devui-animation-ease-in-out-smooth': 'cubic-bezier(0.645, 0.045, 0.355, 1)', 'devui-animation-linear': 'cubic-bezier(0, 0, 1, 1)', // zIndex 'devui-z-index-full-page-overlay': '1080', 'devui-z-index-pop-up': '1060', 'devui-z-index-dropdown': '1052', 'devui-z-index-modal': '1050', 'devui-z-index-drawer': '1040', 'devui-z-index-framework': '1000' }, isDark: false, }); export const devuiGreenTheme: Theme = new Theme({ id: 'avenueui-green-theme', name: 'Green - Light Mode', cnName: '绿色主题', data: { ...devuiLightTheme.data, 'devui-global-bg': '#f3f8f7', 'devui-brand': '#3DCCA6', 'devui-brand-foil': '#7fdac1', 'devui-brand-hover': '#6DDEBB', 'devui-brand-active': '#07c693', 'devui-brand-active-focus': '#369676', 'devui-link': '#07c693', 'devui-link-active': '#07c693', 'devui-link-light': '#96fac8', 'devui-link-light-active': '#befade', 'devui-info': '#079CCD', 'devui-initial': '#CCCCCC', 'devui-icon-fill-active': '#3DCCA6', 'devui-icon-fill-active-hover': '#07c693', 'devui-form-control-line-active': '#3DCCA6', 'devui-form-control-line-active-hover': '#2EB28A', 'devui-list-item-active-bg': '#3DCCA6', 'devui-list-item-active-hover-bg': '#07c693', 'devui-list-item-hover-bg': '#f3fef9', 'devui-list-item-hover-text': '#07c693', 'devui-list-item-selected-bg': '#f3fef9', 'devui-list-item-strip-bg': '#f3fef9', 'devui-connected-overlay-line': '#07c693', 'devui-embed-search-bg': '#f3fef9', 'devui-float-block-shadow': 'rgba(94, 224, 181, 0.3)', 'devui-primary': '#3DCCA6', 'devui-primary-hover': '#6DDEBB', 'devui-primary-active': '#369676', 'devui-info-line': '#0486b1', 'devui-info-bg': '#e3f0f5', 'devui-success-line': '#50d492', 'devui-success-bg': '#edfff9', 'devui-primary-line': '#3DCCA6', 'devui-primary-bg': '#f3fef9', 'devui-default-line': '#3DCCA6', 'devui-default-bg': '#f3f8f7', 'devui-primary-disabled': '#c5f0e5', 'devui-icon-fill-active-disabled': '#c5f0e5', 'devui-range-item-hover-bg': '#d8f9ea',}, extends: 'devui-light-theme', isDark: false, }); export const devuiDarkTheme: Theme = new Theme({ id: 'devui-dark-theme', name: 'Dark Mode', cnName: '深色主题', data: { 'devui-global-bg': '#202124', 'devui-global-bg-normal': '#202124', 'devui-base-bg': '#2E2F31', 'devui-base-bg-dark': '#2e2f31', 'devui-brand': '#5e7ce0', 'devui-brand-foil': '#313a61', 'devui-brand-hover': '#425288', 'devui-brand-active': '#526ecc', 'devui-brand-active-focus': '#344899', 'devui-contrast': '#C7000B', 'devui-text': '#E8E8E8', 'devui-text-weak': '#A0A0A0', 'devui-aide-text': '#909090', 'devui-aide-text-stress': '#A0A0A0', 'devui-placeholder': '#8A8A8A', 'devui-light-text': '#ffffff', 'devui-dark-text': '#252b3a', 'devui-link': '#526ECC', 'devui-link-active': '#344899', 'devui-link-light': '#96adfa', 'devui-link-light-active': '#beccfa', 'devui-line': '#505153', 'devui-dividing-line': '#3D3E40', 'devui-block': '#606061', 'devui-area': '#34363A', 'devui-danger': '#f66f6a', 'devui-warning': '#fac20a', 'devui-waiting': '#5e6580', 'devui-success': '#50d4ab', 'devui-info': '#5e7ce0', 'devui-initial': '#64676e', 'devui-unavailable': '#5b5b5c', 'devui-shadow': 'rgba(17, 18, 19, 0.4)', 'devui-light-shadow': 'rgba(17, 18, 19, 0.5)', // 图标 'devui-icon-text': '#E8E8E8', 'devui-icon-bg': '#2E2F31', 'devui-icon-fill': '#606061', 'devui-icon-fill-hover': '#73788a', 'devui-icon-fill-active': '#5e7ce0', 'devui-icon-fill-active-hover': '#526ecc', // 表单 'devui-form-control-line': '#505153', 'devui-form-control-line-hover': '#909090', 'devui-form-control-line-active': '#5e7ce0', 'devui-form-control-line-active-hover': '#344899', 'devui-list-item-active-bg': '#5e7ce0', 'devui-list-item-active-text': '#ffffff', 'devui-list-item-active-hover-bg': '#526ecc', 'devui-list-item-hover-bg': '#383838', 'devui-list-item-hover-text': '#526ecc', 'devui-list-item-selected-bg': '#454545', 'devui-list-item-strip-bg': '#383838', // 禁用 'devui-disabled-bg': '#3D3E44', 'devui-disabled-line': '#505153', 'devui-disabled-text': '#7D7D7D', 'devui-primary-disabled': '#2B3458', 'devui-icon-fill-active-disabled': '#2B3458', // 特殊背景色 'devui-label-bg': '#46443F', 'devui-connected-overlay-bg': '#2F2F2F', 'devui-connected-overlay-line': '#526ecc', 'devui-fullscreen-overlay-bg': '#2E2F31', 'devui-feedback-overlay-bg': '#4C4C4C', 'devui-feedback-overlay-text': '#DFE1E6', 'devui-embed-search-bg': '#383838', 'devui-embed-search-bg-hover': '#3D3E40', 'devui-float-block-shadow': 'rgba(94, 124, 224, 0.3)', 'devui-highlight-overlay': 'rgba(255, 255, 255, 0.1)', 'devui-range-item-hover-bg': '#454545', // 按钮 'devui-primary': '#5e7ce0', 'devui-primary-hover': '#425288', 'devui-primary-active': '#344899', 'devui-contrast-hover': '#D64A52', 'devui-contrast-active': '#B12220', // 状态 'devui-danger-line': '#985C5A', 'devui-danger-bg': '#4B3A39', 'devui-warning-line': '#8D6138', 'devui-warning-bg': '#554434', 'devui-info-line': '#546BB7', 'devui-info-bg': '#383D4F', 'devui-success-line': '#5D887D', 'devui-success-bg': '#304642', 'devui-primary-line': '#546BB7', 'devui-primary-bg': '#383D4F', 'devui-default-line': '#5e7ce0', 'devui-default-bg': '#383838', }, extends: 'devui-light-theme', isDark: true, }); export const avenueuiGreenDarkTheme: Theme = new Theme({ id: 'avenueui-green-dark-theme', name: 'Green - Dark Mode', cnName: '绿色深色主题', data: { ...devuiDarkTheme.data, 'devui-brand': '#3DCCA6', 'devui-brand-foil': '#395e54', 'devui-brand-hover': '#4c9780', 'devui-brand-active': '#07c693', 'devui-brand-active-focus': '#297058', 'devui-link': '#07c693', 'devui-link-active': '#08a57b', 'devui-info': '#046788', 'devui-initial': '#64676e', 'devui-icon-fill-active': '#3DCCA6', 'devui-icon-fill-active-hover': '#07c693', 'devui-form-control-line-active': '#3DCCA6', 'devui-form-control-line-active-hover': '#297058', 'devui-list-item-active-bg': '#3DCCA6', 'devui-list-item-active-hover-bg': '#07c693', 'devui-list-item-hover-text': '#07c693', 'devui-connected-overlay-line': '#07c693', 'devui-embed-search-bg': '#3f4241', 'devui-float-block-shadow': 'rgba(94, 224, 181, 0.3)', 'devui-primary': '#3DCCA6', 'devui-primary-hover': '#6DDEBB', 'devui-primary-active': '#369676', 'devui-info-line': '#035e7c', 'devui-info-bg': '#383c3d', 'devui-primary-line': '#3DCCA6', 'devui-primary-bg': '#3f4241', 'devui-default-line': '#3DCCA6', 'devui-default-bg': '#383838', 'devui-primary-disabled': '#28544B', 'devui-icon-fill-active-disabled': '#28544B',}, extends: 'devui-dark-theme', isDark: true, });
the_stack
namespace pxtmelody { export class MelodyGallery { protected contentDiv: HTMLDivElement; protected containerDiv: HTMLDivElement; protected itemBorderColor: string; protected itemBackgroundColor: string; protected value: string = null; protected visible = false; protected pending: (res: string) => void; protected buttons: HTMLElement[]; private timeouts: number[] = []; // keep track of timeout private numSamples: number = pxtmelody.SampleMelodies.length; constructor() { this.containerDiv = document.createElement("div"); this.containerDiv.setAttribute("id", "melody-editor-gallery-outer"); this.contentDiv = document.createElement("div"); this.contentDiv.setAttribute("id", "melody-editor-gallery"); this.itemBackgroundColor = "#DCDCDC"; this.itemBorderColor = "white"; this.initStyles(); this.containerDiv.appendChild(this.contentDiv); this.containerDiv.style.display = "none"; this.contentDiv.addEventListener("animationend", () => { if (!this.visible) { this.containerDiv.style.display = "none"; } }); this.contentDiv.addEventListener('wheel', e => { e.stopPropagation(); }, true) } getElement() { return this.containerDiv; } getValue() { return this.value; } show(notes: (res: string) => void) { this.pending = notes; this.containerDiv.style.display = "block"; this.buildDom(); this.visible = true; pxt.BrowserUtils.removeClass(this.contentDiv, "hidden-above"); pxt.BrowserUtils.addClass(this.contentDiv, "shown"); } hide() { this.visible = false; pxt.BrowserUtils.removeClass(this.contentDiv, "shown"); pxt.BrowserUtils.addClass(this.contentDiv, "hidden-above"); this.value = null; this.stopMelody(); } clearDomReferences() { this.contentDiv = null; this.containerDiv = null; } layout(left: number, top: number, height: number) { this.containerDiv.style.left = left + "px"; this.containerDiv.style.top = top + "px"; this.containerDiv.style.height = height + "px"; } protected buildDom() { while (this.contentDiv.firstChild) this.contentDiv.removeChild(this.contentDiv.firstChild); const buttonWidth = "255px"; const buttonHeight = "45px"; const samples = pxtmelody.SampleMelodies; this.buttons = []; for (let i = 0; i < samples.length; i++) { this.mkButton(samples[i], i, buttonWidth, buttonHeight); } } protected initStyles() { // Style injected directly because animations are mangled by the less compiler const style = document.createElement("style"); style.textContent = ` #melody-editor-gallery { margin-top: -100%; } #melody-editor-gallery.hidden-above { margin-top: -100%; animation: slide-up 0.2s 0s ease; } #melody-editor-gallery.shown { margin-top: 0px; animation: slide-down 0.2s 0s ease; } @keyframes slide-down { 0% { margin-top: -100%; } 100% { margin-top: 0px; } } @keyframes slide-up { 0% { margin-top: 0px; } 100% { margin-top: -100%; } } `; this.containerDiv.appendChild(style); } protected mkButton(sample: pxtmelody.MelodyInfo, i: number, width: string, height: string) { const outer = mkElement("div", { className: "melody-gallery-button melody-editor-card", role: "menuitem", id: `:${i}` }); const icon = mkElement("i", { className: "music icon melody-icon" }); const label = mkElement("div", { className: "melody-editor-text" }); label.innerText = sample.name; const preview = this.createColorBlock(sample); const leftButton = mkElement("div", { className: "melody-editor-button left-button", role: "button", title: sample.name }, () => this.handleSelection(sample)) leftButton.appendChild(icon); leftButton.appendChild(label); leftButton.appendChild(preview); outer.appendChild(leftButton); const rightButton = mkElement("div", { className: "melody-editor-button right-button", role: "button", title: lf("Preview {0}", sample.name) }, () => this.togglePlay(sample, i)); const playIcon = mkElement("i", { className: "play icon" }); this.buttons[i] = playIcon; rightButton.appendChild(playIcon); outer.appendChild(rightButton); this.contentDiv.appendChild(outer); } protected handleSelection(sample: pxtmelody.MelodyInfo) { if (this.pending) { const notes = this.pending; this.pending = undefined; notes(sample.notes); } } private playNote(note: string, colNumber: number, tempo: number): void { let tone: number = 0; switch (note) { case "C5": tone = 523; break; // Tenor C case "B": tone = 494; break; // Middle B case "A": tone = 440; break; // Middle A case "G": tone = 392; break; // Middle G case "F": tone = 349; break; // Middle F case "E": tone = 330; break; // Middle E case "D": tone = 294; break; // Middle D case "C": tone = 262; break; // Middle C } // start note this.timeouts.push(setTimeout(() => { pxt.AudioContextManager.tone(tone); }, colNumber * this.getDuration(tempo))); // stop note this.timeouts.push(setTimeout(() => { pxt.AudioContextManager.stop(); }, (colNumber + 1) * this.getDuration(tempo))); } // ms to hold note private getDuration(tempo: number): number { return 60000 / tempo; } private previewMelody(sample: pxtmelody.MelodyInfo): void { // stop playing any other melody this.stopMelody(); let notes = sample.notes.split(" "); for (let i = 0; i < notes.length; i++) { this.playNote(notes[i], i, sample.tempo); } } private togglePlay(sample: pxtmelody.MelodyInfo, i: number) { let button = this.buttons[i]; if (pxt.BrowserUtils.containsClass(button, "play icon")) { // check for other stop icons and toggle back to play this.resetPlayIcons(); pxt.BrowserUtils.removeClass(button, "play icon"); pxt.BrowserUtils.addClass(button, "stop icon"); this.previewMelody(sample); // make icon toggle back to play when the melody finishes this.timeouts.push(setTimeout(() => { pxt.BrowserUtils.removeClass(button, "stop icon"); pxt.BrowserUtils.addClass(button, "play icon"); }, (sample.notes.split(" ").length) * this.getDuration(sample.tempo))); } else { pxt.BrowserUtils.removeClass(button, "stop icon"); pxt.BrowserUtils.addClass(button, "play icon"); this.stopMelody(); } } public stopMelody() { while (this.timeouts.length) clearTimeout(this.timeouts.shift()); pxt.AudioContextManager.stop(); } private resetPlayIcons(): void { for (let i = 0; i < this.numSamples; i++) { let button = this.buttons[i]; if (pxt.BrowserUtils.containsClass(button, "stop icon")) { pxt.BrowserUtils.removeClass(button, "stop icon"); pxt.BrowserUtils.addClass(button, "play icon"); break; } } } // create color representation of melody private createColorBlock(sample: pxtmelody.MelodyInfo): HTMLDivElement { let colorBlock = document.createElement("div"); pxt.BrowserUtils.addClass(colorBlock, "melody-color-block"); let notes = sample.notes.split(" "); for (let i = 0; i < notes.length; i++) { let className = pxtmelody.getColorClass(pxtmelody.noteToRow(notes[i])); let colorDiv = document.createElement("div"); // create rounded effect on edge divs and fill in color if (i == 0) { pxt.BrowserUtils.addClass(colorDiv, "left-edge sliver " + className); } else if (i == notes.length - 1) { pxt.BrowserUtils.addClass(colorDiv, "right-edge sliver " + className); } else { pxt.BrowserUtils.addClass(colorDiv, "sliver " + className); } colorBlock.appendChild(colorDiv); } return colorBlock; } } function mkElement(tag: string, props?: {[index: string]: string | number}, onClick?: () => void): HTMLElement { const el = document.createElement(tag); return initElement(el, props, onClick); } function initElement(el: HTMLElement, props?: {[index: string]: string | number}, onClick?: () => void) { if (props) { for (const key of Object.keys(props)) { if (key === "className") el.setAttribute("class", props[key] + "") else el.setAttribute(key, props[key] + ""); } } if (onClick) { el.addEventListener("click", onClick); } return el; } }
the_stack
import { Component, DebugElement, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, flush } from '@angular/core/testing'; import { FormControl, FormsModule, NgModel, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { McToggleComponent, McToggleModule } from './index'; describe('McToggle', () => { let fixture: ComponentFixture<any>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, McToggleModule, FormsModule, ReactiveFormsModule], declarations: [ SingleToggle, ToggleWithFormDirectives, MultipleToggles, ToggleWithTabIndex, ToggleWithAriaLabel, ToggleWithAriaLabelledby, ToggleWithNameAttribute, ToggleWithFormControl, ToggleWithoutLabel, ToggleUsingViewChild ] }); TestBed.compileComponents(); })); describe('basic behaviors', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let toggleInstance: McToggleComponent; let testComponent: SingleToggle; let inputElement: HTMLInputElement; let labelElement: HTMLLabelElement; beforeEach(() => { fixture = TestBed.createComponent(SingleToggle); fixture.detectChanges(); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; toggleInstance = toggleDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); labelElement = <HTMLLabelElement> toggleNativeElement.querySelector('label'); }); it('should add and remove the checked state', () => { expect(toggleInstance.checked).toBe(false); expect(inputElement.checked).toBe(false); testComponent.value = true; fixture.detectChanges(); expect(toggleInstance.checked).toBe(true); expect(inputElement.checked).toBe(true); testComponent.value = false; fixture.detectChanges(); expect(toggleInstance.checked).toBe(false); expect(inputElement.checked).toBe(false); }); it('should change native element checked when check programmatically', () => { expect(inputElement.checked).toBe(false); toggleInstance.checked = true; fixture.detectChanges(); expect(inputElement.checked).toBe(true); }); it('should toggle checked state on click', () => { expect(toggleInstance.checked).toBe(false); labelElement.click(); fixture.detectChanges(); expect(toggleInstance.checked).toBe(true); labelElement.click(); fixture.detectChanges(); expect(toggleInstance.checked).toBe(false); }); it('should add and remove disabled state', () => { expect(toggleInstance.disabled).toBe(false); expect(toggleNativeElement.classList).not.toContain('mc-disabled'); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); testComponent.isDisabled = true; fixture.detectChanges(); expect(toggleInstance.disabled).toBe(true); expect(toggleNativeElement.classList).toContain('mc-disabled'); expect(inputElement.disabled).toBe(true); testComponent.isDisabled = false; fixture.detectChanges(); expect(toggleInstance.disabled).toBe(false); expect(toggleNativeElement.classList).not.toContain('mc-disabled'); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); }); it('should not toggle `checked` state upon interation while disabled', () => { testComponent.isDisabled = true; fixture.detectChanges(); toggleNativeElement.click(); expect(toggleInstance.checked).toBe(false); }); it('should preserve the user-provided id', () => { expect(toggleNativeElement.id).toBe('simple-check'); expect(inputElement.id).toBe('simple-check-input'); }); it('should generate a unique id for the toggle input if no id is set', () => { testComponent.toggleId = null; fixture.detectChanges(); expect(toggleInstance.inputId).toMatch(/mc-toggle-\d+/); expect(inputElement.id).toBe(toggleInstance.inputId); }); it('should project the toggle content into the label element', () => { const label = <HTMLLabelElement> toggleNativeElement.querySelector('.mc-toggle-label'); expect(label.textContent!.trim()).toBe('Simple toggle'); }); it('should make the host element a tab stop', () => { expect(inputElement.tabIndex).toBe(0); }); it('should add a css class to position the label before the toggle', () => { testComponent.labelPos = 'left'; fixture.detectChanges(); expect(toggleNativeElement.querySelector('.left')).not.toBeNull(); }); it('should not trigger the click event multiple times', () => { spyOn(testComponent, 'onToggleClick'); expect(inputElement.checked).toBe(false); labelElement.click(); fixture.detectChanges(); expect(inputElement.checked).toBe(true); expect(testComponent.onToggleClick).toHaveBeenCalledTimes(1); }); it('should trigger a change event when the native input does', fakeAsync(() => { spyOn(testComponent, 'onToggleChange'); expect(inputElement.checked).toBe(false); labelElement.click(); fixture.detectChanges(); expect(inputElement.checked).toBe(true); fixture.detectChanges(); flush(); expect(testComponent.onToggleChange).toHaveBeenCalledTimes(1); })); it('should not trigger the change event by changing the native value', fakeAsync(() => { spyOn(testComponent, 'onToggleChange'); expect(inputElement.checked).toBe(false); testComponent.value = true; fixture.detectChanges(); expect(inputElement.checked).toBe(true); fixture.detectChanges(); flush(); // The change event shouldn't fire, because the value change was not caused // by any interaction. expect(testComponent.onToggleChange).not.toHaveBeenCalled(); })); it('should focus on underlying input element when focus() is called', () => { expect(document.activeElement).not.toBe(inputElement); toggleInstance.focus(); fixture.detectChanges(); expect(document.activeElement).toBe(inputElement); }); describe('color behaviour', () => { it('should apply class based on color attribute', () => { testComponent.toggleColor = 'primary'; fixture.detectChanges(); expect(toggleNativeElement.classList.contains('mc-primary')).toBe(true); testComponent.toggleColor = 'accent'; fixture.detectChanges(); expect(toggleNativeElement.classList.contains('mc-accent')).toBe(true); }); it('should should not clear previous defined classes', () => { toggleNativeElement.classList.add('custom-class'); testComponent.toggleColor = 'primary'; fixture.detectChanges(); expect(toggleNativeElement.classList.contains('mc-primary')).toBe(true); expect(toggleNativeElement.classList.contains('custom-class')).toBe(true); testComponent.toggleColor = 'accent'; fixture.detectChanges(); expect(toggleNativeElement.classList.contains('mc-primary')).toBe(false); expect(toggleNativeElement.classList.contains('mc-accent')).toBe(true); expect(toggleNativeElement.classList.contains('custom-class')).toBe(true); }); }); }); describe('aria-label ', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let inputElement: HTMLInputElement; it('should use the provided aria-label', () => { fixture = TestBed.createComponent(ToggleWithAriaLabel); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-label')).toBe('Super effective'); }); it('should not set the aria-label attribute if no value is provided', () => { fixture = TestBed.createComponent(SingleToggle); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('input').hasAttribute('aria-label')).toBe(false); }); }); describe('with provided aria-labelledby ', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let inputElement: HTMLInputElement; it('should use the provided aria-labelledby', () => { fixture = TestBed.createComponent(ToggleWithAriaLabelledby); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-labelledby')).toBe('some-id'); }); it('should not assign aria-labelledby if none is provided', () => { fixture = TestBed.createComponent(SingleToggle); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); fixture.detectChanges(); expect(inputElement.getAttribute('aria-labelledby')).toBe(null); }); }); describe('with provided tabIndex', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let testComponent: ToggleWithTabIndex; let inputElement: HTMLInputElement; beforeEach(() => { fixture = TestBed.createComponent(ToggleWithTabIndex); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); }); it('should preserve any given tabIndex', () => { expect(inputElement.tabIndex).toBe(7); }); it('should preserve given tabIndex when the toggle is disabled then enabled', () => { testComponent.isDisabled = true; fixture.detectChanges(); testComponent.customTabIndex = 13; fixture.detectChanges(); testComponent.isDisabled = false; fixture.detectChanges(); expect(inputElement.tabIndex).toBe(13); }); }); describe('using ViewChild', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let testComponent: ToggleUsingViewChild; beforeEach(() => { fixture = TestBed.createComponent(ToggleUsingViewChild); fixture.detectChanges(); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; testComponent = fixture.debugElement.componentInstance; }); it('should toggle disabledness correctly', () => { const toggleInstance = toggleDebugElement.componentInstance; const inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); expect(toggleInstance.disabled).toBe(false); expect(toggleNativeElement.classList).not.toContain('mc-disabled'); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); testComponent.isDisabled = true; fixture.detectChanges(); expect(toggleInstance.disabled).toBe(true); expect(toggleNativeElement.classList).toContain('mc-disabled'); expect(inputElement.disabled).toBe(true); testComponent.isDisabled = false; fixture.detectChanges(); expect(toggleInstance.disabled).toBe(false); expect(toggleNativeElement.classList).not.toContain('mc-disabled'); expect(inputElement.tabIndex).toBe(0); expect(inputElement.disabled).toBe(false); }); }); describe('with multiple toggles', () => { beforeEach(() => { fixture = TestBed.createComponent(MultipleToggles); fixture.detectChanges(); }); it('should assign a unique id to each toggle', () => { const [firstId, secondId] = fixture.debugElement.queryAll(By.directive(McToggleComponent)) .map((debugElement) => debugElement.nativeElement.querySelector('input').id); expect(firstId).toMatch(/mc-toggle-\d+-input/); expect(secondId).toMatch(/mc-toggle-\d+-input/); expect(firstId).not.toEqual(secondId); }); }); describe('with ngModel', () => { let toggleDebugElement: DebugElement; let toggleNativeElement: HTMLElement; let toggleInstance: McToggleComponent; let inputElement: HTMLInputElement; beforeEach(() => { fixture = TestBed.createComponent(ToggleWithFormDirectives); fixture.detectChanges(); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleNativeElement = toggleDebugElement.nativeElement; toggleInstance = toggleDebugElement.componentInstance; inputElement = <HTMLInputElement> toggleNativeElement.querySelector('input'); }); it('should be in pristine, untouched, and valid states initially', fakeAsync(() => { flush(); const toggleElement = fixture.debugElement.query(By.directive(McToggleComponent)); const ngModel = toggleElement.injector.get<NgModel>(NgModel); expect(ngModel.valid).toBe(true); expect(ngModel.pristine).toBe(true); expect(ngModel.touched).toBe(false); // TODO(jelbourn): test that `touched` and `pristine` state are modified appropriately. // This is currently blocked on issues with async() and fakeAsync(). })); it('should toggle checked state on click', () => { expect(toggleInstance.checked).toBe(false); inputElement.click(); fixture.detectChanges(); expect(toggleInstance.checked).toBe(true); inputElement.click(); fixture.detectChanges(); expect(toggleInstance.checked).toBe(false); }); }); describe('with name attribute', () => { beforeEach(() => { fixture = TestBed.createComponent(ToggleWithNameAttribute); fixture.detectChanges(); }); it('should forward name value to input element', () => { const toggleElement = fixture.debugElement.query(By.directive(McToggleComponent)); const inputElement = <HTMLInputElement> toggleElement.nativeElement.querySelector('input'); expect(inputElement.getAttribute('name')).toBe('test-name'); }); }); describe('with form control', () => { let toggleDebugElement: DebugElement; let toggleInstance: McToggleComponent; let testComponent: ToggleWithFormControl; let inputElement: HTMLInputElement; beforeEach(() => { fixture = TestBed.createComponent(ToggleWithFormControl); fixture.detectChanges(); toggleDebugElement = fixture.debugElement.query(By.directive(McToggleComponent)); toggleInstance = toggleDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; inputElement = <HTMLInputElement> toggleDebugElement.nativeElement.querySelector('input'); }); it('should toggle the disabled state', () => { expect(toggleInstance.disabled).toBe(false); testComponent.formControl.disable(); fixture.detectChanges(); expect(toggleInstance.disabled).toBe(true); expect(inputElement.disabled).toBe(true); testComponent.formControl.enable(); fixture.detectChanges(); expect(toggleInstance.disabled).toBe(false); expect(inputElement.disabled).toBe(false); }); }); describe('without label', () => { let toggleInnerContainer: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(ToggleWithoutLabel); const toggleDebugEl = fixture.debugElement.query(By.directive(McToggleComponent)); toggleInnerContainer = toggleDebugEl .query(By.css('.mc-toggle__container')).nativeElement; }); it('should not add the "name" attribute if it is not passed in', () => { fixture.detectChanges(); expect(toggleInnerContainer.querySelector('input')!.hasAttribute('name')).toBe(false); }); it('should not add the "value" attribute if it is not passed in', () => { fixture.detectChanges(); expect(toggleInnerContainer.querySelector('input')!.hasAttribute('value')).toBe(false); }); }); }); @Component({ template: ` <div (click)="parentElementClicked = true" (keyup)="parentElementKeyedUp = true"> <mc-toggle [id]="toggleId" [labelPosition]="labelPos" [checked]="value" [disabled]="isDisabled" [color]="toggleColor" (click)="onToggleClick($event)" (change)="onToggleChange($event)"> Simple toggle </mc-toggle> </div>` }) class SingleToggle { labelPos: 'left' | 'right' = 'left'; value: boolean = false; isDisabled: boolean = false; parentElementClicked: boolean = false; parentElementKeyedUp: boolean = false; toggleId: string | null = 'simple-check'; toggleColor: string = 'primary'; onToggleClick: (event?: Event) => void = () => {}; onToggleChange: (event?: any) => void = () => {}; } @Component({ template: ` <form> <mc-toggle name="cb" [(ngModel)]="isGood">Be good</mc-toggle> </form> ` }) class ToggleWithFormDirectives { isGood: boolean = false; } @Component(({ template: ` <mc-toggle>Option 1</mc-toggle> <mc-toggle>Option 2</mc-toggle> ` })) class MultipleToggles {} @Component({ template: ` <mc-toggle [tabIndex]="customTabIndex" [disabled]="isDisabled"> </mc-toggle>` }) class ToggleWithTabIndex { customTabIndex: number = 7; isDisabled: boolean = false; } @Component({ template: ` <mc-toggle></mc-toggle>` }) class ToggleUsingViewChild { @ViewChild(McToggleComponent, {static: false}) toggle; set isDisabled(value: boolean) { this.toggle.disabled = value; } } @Component({ template: `<mc-toggle aria-label="Super effective"></mc-toggle>` }) class ToggleWithAriaLabel { } @Component({ template: `<mc-toggle aria-labelledby="some-id"></mc-toggle>` }) class ToggleWithAriaLabelledby { } @Component({ template: `<mc-toggle name="test-name"></mc-toggle>` }) class ToggleWithNameAttribute { } @Component({ template: `<mc-toggle [formControl]="formControl"></mc-toggle>` }) class ToggleWithFormControl { formControl = new FormControl(); } @Component({ template: `<mc-toggle>{{ label }}</mc-toggle>` }) class ToggleWithoutLabel { label: string; }
the_stack
import * as ts from 'typescript'; import * as Lint from 'tslint'; import * as tsutils from 'tsutils'; import { ExtendedMetadata } from './utils/ExtendedMetadata'; import { Utils } from './utils/Utils'; import { getImplicitRole } from './utils/getImplicitRole'; import { getJsxAttributesFromJsxElement, getStringLiteral, isEmpty } from './utils/JsxAttribute'; import { isObject } from './utils/TypeGuard'; export const OPTION_IGNORE_CASE: string = 'ignore-case'; export const OPTION_IGNORE_WHITESPACE: string = 'ignore-whitespace'; const ROLE_STRING: string = 'role'; export const NO_HASH_FAILURE_STRING: string = 'Do not use # as anchor href.'; export const MISSING_HREF_FAILURE_STRING: string = 'Do not leave href undefined or null'; export const LINK_TEXT_TOO_SHORT_FAILURE_STRING: string = 'Link text or the alt text of image in link should be at least 4 characters long. ' + "If you are not using <a> element as anchor, please specify explicit role, e.g. role='button'"; export const UNIQUE_ALT_FAILURE_STRING: string = 'Links with images and text content, the alt attribute should be unique to the text content or empty.'; export const SAME_HREF_SAME_TEXT_FAILURE_STRING: string = 'Links with the same HREF should have the same link text.'; export const DIFFERENT_HREF_DIFFERENT_TEXT_FAILURE_STRING: string = 'Links that point to different HREFs should have different link text.'; export const ACCESSIBLE_HIDDEN_CONTENT_FAILURE_STRING: string = 'Link content can not be hidden for screen-readers by using aria-hidden attribute.'; interface Options { ignoreCase: boolean; ignoreWhitespace: string; } export class Rule extends Lint.Rules.AbstractRule { public static metadata: ExtendedMetadata = { ruleName: 'react-a11y-anchors', type: 'functionality', description: 'For accessibility of your website, anchor elements must have a href different from # and a text longer than 4.', rationale: `References: <ul> <li><a href="http://oaa-accessibility.org/wcag20/rule/38">WCAG Rule 38: Link text should be as least four 4 characters long</a></li> <li><a href="http://oaa-accessibility.org/wcag20/rule/39">WCAG Rule 39: Links with the same HREF should have the same link text</a></li> <li><a href="http://oaa-accessibility.org/wcag20/rule/41">WCAG Rule 41: Links that point to different HREFs should have different link text</a></li> <li><a href="http://oaa-accessibility.org/wcag20/rule/43">WCAG Rule 43: Links with images and text content, the alt attribute should be unique to the text content or empty</a></li> </ul>`, options: { type: 'array', items: { type: 'string', enum: [OPTION_IGNORE_CASE, OPTION_IGNORE_WHITESPACE] }, minLength: 0, maxLength: 2 }, optionsDescription: Lint.Utils.dedent` Optional arguments to relax the same HREF same link text rule are provided: * \`${OPTION_IGNORE_CASE}\` ignore differences in cases. * \`{"${OPTION_IGNORE_WHITESPACE}": "trim"}\` ignore differences only in leading/trailing whitespace. * \`{"${OPTION_IGNORE_WHITESPACE}": "all"}\` ignore differences in all whitespace. `, typescriptOnly: true, issueClass: 'Non-SDL', issueType: 'Warning', severity: 'Low', level: 'Opportunity for Excellence', group: 'Accessibility' }; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { if (sourceFile.languageVariant === ts.LanguageVariant.JSX) { return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions())); } return []; } private parseOptions(options: Lint.IOptions): Options { const parsed: Options = { ignoreCase: false, ignoreWhitespace: '' }; options.ruleArguments.forEach((opt: unknown) => { if (typeof opt === 'string' && opt === OPTION_IGNORE_CASE) { parsed.ignoreCase = true; } if (isObject(opt)) { parsed.ignoreWhitespace = <string>opt[OPTION_IGNORE_WHITESPACE]; } }); return parsed; } } function walk(ctx: Lint.WalkContext<Options>) { const anchorInfoList: IAnchorInfo[] = []; function validateAllAnchors(): void { const sameHrefDifferentTexts: IAnchorInfo[] = []; const differentHrefSameText: IAnchorInfo[] = []; while (anchorInfoList.length > 0) { // tslint:disable-next-line:no-non-null-assertion const current: IAnchorInfo = anchorInfoList.shift()!; anchorInfoList.forEach( (anchorInfo: IAnchorInfo): void => { if ( current.href && current.href === anchorInfo.href && !compareAnchorsText(current, anchorInfo) && !Utils.contains(sameHrefDifferentTexts, anchorInfo) ) { // Same href - different text... sameHrefDifferentTexts.push(anchorInfo); ctx.addFailureAt(anchorInfo.start, anchorInfo.width, SAME_HREF_SAME_TEXT_FAILURE_STRING + firstPosition(current)); } if ( current.href !== anchorInfo.href && compareAnchorsText(current, anchorInfo) && !Utils.contains(differentHrefSameText, anchorInfo) ) { // Different href - same text... differentHrefSameText.push(anchorInfo); ctx.addFailureAt( anchorInfo.start, anchorInfo.width, DIFFERENT_HREF_DIFFERENT_TEXT_FAILURE_STRING + firstPosition(current) ); } } ); } } function compareAnchorsText(anchor1: IAnchorInfo, anchor2: IAnchorInfo): boolean { let text1: string = anchor1.text; let text2: string = anchor2.text; let altText1: string = anchor1.altText; let altText2: string = anchor2.altText; if (ctx.options.ignoreCase) { text1 = text1.toLowerCase(); text2 = text2.toLowerCase(); altText1 = altText1.toLowerCase(); altText2 = altText2.toLowerCase(); } if (ctx.options.ignoreWhitespace === 'trim') { text1 = text1.trim(); text2 = text2.trim(); altText1 = altText1.trim(); altText2 = altText2.trim(); } if (ctx.options.ignoreWhitespace === 'all') { const regex: RegExp = /\s/g; text1 = text1.replace(regex, ''); text2 = text2.replace(regex, ''); altText1 = altText1.replace(regex, ''); altText2 = altText2.replace(regex, ''); } return text1 === text2 && altText1 === altText2; } function firstPosition(anchorInfo: IAnchorInfo): string { const startPosition = ctx.sourceFile.getLineAndCharacterOfPosition(Math.min(anchorInfo.start, ctx.sourceFile.end)); // Position is zero based - add 1... const character: number = startPosition.character + 1; const line: number = startPosition.line + 1; return ` First link at character: ${character} line: ${line}`; } function validateAnchor(parent: ts.Node, openingElement: ts.JsxOpeningLikeElement): void { if (openingElement.tagName.getText() === 'a') { const hrefAttribute = getAttribute(openingElement, 'href'); const anchorInfo: IAnchorInfo = { href: hrefAttribute ? getStringLiteral(hrefAttribute) || '' : '', text: anchorText(parent), altText: imageAlt(parent), hasAriaHiddenCount: jsxElementAriaHidden(parent), start: parent.getStart(), width: parent.getWidth() }; if (isEmpty(hrefAttribute)) { ctx.addFailureAt(anchorInfo.start, anchorInfo.width, MISSING_HREF_FAILURE_STRING); } if (anchorInfo.href === '#') { ctx.addFailureAt(anchorInfo.start, anchorInfo.width, NO_HASH_FAILURE_STRING); } if (anchorInfo.hasAriaHiddenCount > 0) { ctx.addFailureAt(anchorInfo.start, anchorInfo.width, ACCESSIBLE_HIDDEN_CONTENT_FAILURE_STRING); } if (anchorInfo.altText && anchorInfo.altText === anchorInfo.text) { ctx.addFailureAt(anchorInfo.start, anchorInfo.width, UNIQUE_ALT_FAILURE_STRING); } const anchorInfoTextLength: number = anchorInfo.text ? anchorInfo.text.length : 0; const anchorImageAltTextLength: number = anchorInfo.altText ? anchorInfo.altText.length : 0; if (anchorRole(openingElement) === 'link' && anchorInfoTextLength < 4 && anchorImageAltTextLength < 4) { ctx.addFailureAt(anchorInfo.start, anchorInfo.width, LINK_TEXT_TOO_SHORT_FAILURE_STRING); } anchorInfoList.push(anchorInfo); } } function getAttribute(openingElement: ts.JsxOpeningLikeElement, attributeName: string): ts.JsxAttribute { const attributes: { [propName: string]: ts.JsxAttribute } = getJsxAttributesFromJsxElement(openingElement); return attributes[attributeName]; } /** * Return a string which contains literal text and text in 'alt' attribute. */ function anchorText(root: ts.Node | undefined, isChild: boolean = false): string { let title: string = ''; if (root === undefined) { return title; } if (root.kind === ts.SyntaxKind.JsxElement) { const jsxElement: ts.JsxElement = <ts.JsxElement>root; jsxElement.children.forEach( (child: ts.JsxChild): void => { title += anchorText(child, true); } ); } else if (root.kind === ts.SyntaxKind.JsxText) { const jsxText: ts.JsxText = <ts.JsxText>root; title += jsxText.getText(); } else if (root.kind === ts.SyntaxKind.StringLiteral) { const literal: ts.StringLiteral = <ts.StringLiteral>root; title += literal.text; } else if (root.kind === ts.SyntaxKind.JsxExpression) { const expression: ts.JsxExpression = <ts.JsxExpression>root; title += anchorText(expression.expression); } else if (isChild && root.kind === ts.SyntaxKind.JsxSelfClosingElement) { const jsxSelfClosingElement = <ts.JsxSelfClosingElement>root; if (jsxSelfClosingElement.tagName.getText() !== 'img') { title += '<component>'; } } else if (root.kind !== ts.SyntaxKind.JsxSelfClosingElement) { title += '<unknown>'; } return title; } function anchorRole(root: ts.Node): string | undefined { const attributesInElement: { [propName: string]: ts.JsxAttribute } = getJsxAttributesFromJsxElement(root); const roleProp: ts.JsxAttribute = attributesInElement[ROLE_STRING]; // If role attribute is specified, get the role value. Otherwise get the implicit role from tag name. return roleProp ? getStringLiteral(roleProp) : getImplicitRole(root); } function imageAltAttribute(openingElement: ts.JsxOpeningLikeElement): string { if (openingElement.tagName.getText() === 'img') { const altAttribute = getStringLiteral(getAttribute(openingElement, 'alt')); return altAttribute === undefined ? '<unknown>' : altAttribute; } return ''; } function imageAlt(root: ts.Node): string { let altText: string = ''; if (root.kind === ts.SyntaxKind.JsxElement) { const jsxElement: ts.JsxElement = <ts.JsxElement>root; altText += imageAltAttribute(jsxElement.openingElement); jsxElement.children.forEach( (child: ts.JsxChild): void => { altText += imageAlt(child); } ); } if (root.kind === ts.SyntaxKind.JsxSelfClosingElement) { const jsxSelfClosingElement: ts.JsxSelfClosingElement = <ts.JsxSelfClosingElement>root; altText += imageAltAttribute(jsxSelfClosingElement); } return altText; } function ariaHiddenAttribute(openingElement: ts.JsxOpeningLikeElement): boolean { return getAttribute(openingElement, 'aria-hidden') === undefined; } function jsxElementAriaHidden(root: ts.Node): number { let hasAriaHiddenCount: number = 0; if (root.kind === ts.SyntaxKind.JsxElement) { const jsxElement: ts.JsxElement = <ts.JsxElement>root; hasAriaHiddenCount += ariaHiddenAttribute(jsxElement.openingElement) ? 0 : 1; jsxElement.children.forEach( (child: ts.JsxChild): void => { hasAriaHiddenCount += jsxElementAriaHidden(child); } ); } if (root.kind === ts.SyntaxKind.JsxSelfClosingElement) { const jsxSelfClosingElement: ts.JsxSelfClosingElement = <ts.JsxSelfClosingElement>root; hasAriaHiddenCount += ariaHiddenAttribute(jsxSelfClosingElement) ? 0 : 1; } return hasAriaHiddenCount; } function cb(node: ts.Node): void { if (tsutils.isJsxSelfClosingElement(node)) { validateAnchor(node, node); } else if (tsutils.isJsxElement(node)) { validateAnchor(node, node.openingElement); } return ts.forEachChild(node, cb); } ts.forEachChild(ctx.sourceFile, cb); validateAllAnchors(); } interface IAnchorInfo { href: string; text: string; altText: string; hasAriaHiddenCount: number; start: number; width: number; }
the_stack
import { Component, ComponentInterface, Element, Event, EventEmitter, h, Listen, Method, Prop, QueueApi, State, } from '@stencil/core'; import { SuperTabsConfig } from '../interface'; import { checkGesture, debugLog, getTs, pointerCoord, scrollEl, STCoord } from '../utils'; @Component({ tag: 'super-tabs-container', styleUrl: 'super-tabs-container.component.scss', shadow: true, }) export class SuperTabsContainerComponent implements ComponentInterface { @Element() el!: HTMLSuperTabsContainerElement; /** @internal */ @Prop({ mutable: true }) config?: SuperTabsConfig; /** @internal */ @Prop({ context: 'queue' }) queue!: QueueApi; /** * Enable/disable swiping */ @Prop() swipeEnabled: boolean = true; /** * Set to true to automatically scroll to the top of the tab when the button is clicked while the tab is * already selected. */ @Prop() autoScrollTop: boolean = false; /** * Emits an event when the active tab changes. * An active tab is the tab that the user looking at. * * This event emitter will not notify you if the user has changed the current active tab. * If you need that information, you should use the `tabChange` event emitted by the `super-tabs` element. */ @Event() activeTabIndexChange!: EventEmitter<number>; /** * Emits events when the container moves. * Selected tab index represents what the user should be seeing. * If you receive a decimal as the emitted number, it means that the container is moving between tabs. * This number is used for animations, and can be used for high tab customizations. */ @Event() selectedTabIndexChange!: EventEmitter<number>; @State() tabs: HTMLSuperTabElement[] = []; private initialCoords: STCoord | undefined; private lastPosX: number | undefined; private isDragging: boolean = false; private initialTimestamp?: number; private _activeTabIndex: number | undefined; private _selectedTabIndex?: number; private leftThreshold: number = 0; private rightThreshold: number = 0; private scrollWidth: number = 0; private slot!: HTMLSlotElement; private ready?: boolean; private width: number = 0; async componentDidLoad() { this.debug('componentDidLoad'); this.updateWidth(); await this.indexTabs(); this.slot = this.el.shadowRoot!.querySelector('slot') as HTMLSlotElement; this.slot.addEventListener('slotchange', this.onSlotChange.bind(this)); } private async onSlotChange() { this.debug('onSlotChange', this.tabs.length); this.updateWidth(); this.indexTabs(); } async componentDidRender() { this.updateWidth(); } /** * @internal */ @Method() async reindexTabs() { this.updateWidth(); await this.indexTabs(); } /** * @internal * * Moves the container to align with the specified tab index * @param index {number} Index of the tab * @param animate {boolean} Whether to animate the transition */ @Method() moveContainerByIndex(index: number, animate?: boolean): Promise<void> { const scrollX = this.indexToPosition(index); if (scrollX === 0 && index > 0) { return Promise.resolve(); } return this.moveContainer(scrollX, animate); } /** * @internal * * Sets the scrollLeft property of the container * @param scrollX {number} * @param animate {boolean} */ @Method() moveContainer(scrollX: number, animate?: boolean): Promise<void> { if (animate) { scrollEl(this.el, scrollX, this.config!.nativeSmoothScroll!, this.config!.transitionDuration); } else { this.el.scroll(scrollX, 0); } return Promise.resolve(); } /** @internal */ @Method() async setActiveTabIndex(index: number, moveContainer: boolean = true, animate: boolean = true): Promise<void> { this.debug('setActiveTabIndex', index); if (this._activeTabIndex === index) { if (!this.autoScrollTop) { return; } await this.scrollToTop(); } if (moveContainer) { await this.moveContainerByIndex(index, animate); } await this.updateActiveTabIndex(index, false); } /** * Scroll the active tab to the top. */ @Method() async scrollToTop() { if (this._activeTabIndex === undefined || this.tabs === undefined) { this.debug('activeTabIndex or tabs was undefined'); return; } const current = this.tabs[this._activeTabIndex]; this.queue.read(() => { if (!current) { this.debug('Current active tab was undefined in scrollToTop'); return; } // deepcode ignore PromiseNotCaughtGeneral: <comment the reason here> current.getRootScrollableEl().then((el) => { if (el) { scrollEl(el, 0, this.config!.nativeSmoothScroll!, this.config!.transitionDuration); } }); }); } private updateActiveTabIndex(index: number, emit: boolean = true) { this.debug('updateActiveTabIndex', index, emit, this._activeTabIndex); this._activeTabIndex = index; emit && this.activeTabIndexChange.emit(this._activeTabIndex); this.lazyLoadTabs(); } private updateSelectedTabIndex(index: number) { if (index === this._selectedTabIndex) { return; } this._selectedTabIndex = index; this.selectedTabIndexChange.emit(this._selectedTabIndex); } @Listen('touchstart') async onTouchStart(ev: TouchEvent) { if (!this.swipeEnabled) { return; } if (this.config!.avoidElements) { let avoid: boolean = false; let element: any = ev.target; if (element) { do { if (typeof element.getAttribute === 'function' && element.getAttribute('avoid-super-tabs')) { return; } element = element.parentElement; } while (element && !avoid); } } const coords = pointerCoord(ev); this.updateWidth(); const vw = this.width; if (coords.x < this.leftThreshold || coords.x > vw - this.rightThreshold) { // ignore this gesture, it started in the side menu touch zone return; } if (this.config!.shortSwipeDuration! > 0) { this.initialTimestamp = getTs(); } this.initialCoords = coords; this.lastPosX = coords.x; } @Listen('click', { passive: false, capture: true }) async onClick(ev: TouchEvent) { if (this.isDragging) { ev.stopImmediatePropagation(); ev.preventDefault(); } } @Listen('touchmove', { passive: true, capture: true }) async onTouchMove(ev: TouchEvent) { if (!this.swipeEnabled || !this.initialCoords || typeof this.lastPosX !== 'number') { return; } const coords = pointerCoord(ev); if (!this.isDragging) { if (!checkGesture(coords, this.initialCoords, this.config!)) { if (Math.abs(coords.y - this.initialCoords.y) > 100) { this.initialCoords = void 0; this.lastPosX = void 0; } return; } this.isDragging = true; } // stop anything else from capturing these events, to make sure the content doesn't slide if (!this.config!.allowElementScroll) { ev.stopImmediatePropagation(); } // get delta X const deltaX: number = this.lastPosX! - coords.x; if (deltaX === 0) { return; } const scrollX = Math.max(0, Math.min(this.scrollWidth - this.width, this.el.scrollLeft + deltaX)); if (Math.floor(scrollX) === Math.floor(this.el.scrollLeft)) { return; } const index = Math.round(this.positionToIndex(scrollX) * 100) / 100; this.updateSelectedTabIndex(index); // update last X value this.lastPosX = coords.x; this.el.scroll(scrollX, 0); } @Listen('touchend', { passive: false, capture: true }) async onTouchEnd(ev: TouchEvent) { if (!this.swipeEnabled || !this.isDragging) { return; } const coords = pointerCoord(ev); const deltaTime: number = getTs() - this.initialTimestamp!; const shortSwipe = this.config!.shortSwipeDuration! > 0 && deltaTime <= this.config!.shortSwipeDuration!; const shortSwipeDelta = coords.x - this.initialCoords!.x; let selectedTabIndex = this.calcSelectedTab(); const expectedTabIndex = Math.round(selectedTabIndex); if (shortSwipe && expectedTabIndex === this._activeTabIndex) { selectedTabIndex += shortSwipeDelta > 0 ? -1 : 1; } selectedTabIndex = this.normalizeSelectedTab(selectedTabIndex); this.updateActiveTabIndex(selectedTabIndex); this.moveContainerByIndex(selectedTabIndex, true); this.isDragging = false; this.initialCoords = void 0; this.lastPosX = void 0; } private updateWidth() { const boundingRect = this.el.getBoundingClientRect(); this.width = Math.round(boundingRect.width * 10000) / 10000; } private async indexTabs() { if (this.width === 0) { requestAnimationFrame(() => { this.updateWidth(); this.indexTabs(); }); return; } const tabs = Array.from(this.el.querySelectorAll('super-tab')); this.scrollWidth = this.width * tabs.length; this.debug('indexTab', this.scrollWidth, this.width); await Promise.all(tabs.map((t) => t.componentOnReady())); this.tabs = tabs; const activeTabIndex = this._activeTabIndex if (this.ready && typeof activeTabIndex === 'number') { this.moveContainerByIndex(activeTabIndex, true); this.lazyLoadTabs(); } if (this.config) { switch (this.config.sideMenu) { case 'both': this.rightThreshold = this.leftThreshold = this.config.sideMenuThreshold || 0; break; case 'left': this.leftThreshold = this.config.sideMenuThreshold || 0; break; case 'right': this.rightThreshold = this.config.sideMenuThreshold || 0; break; } } if (activeTabIndex !== undefined) { this.moveContainerByIndex(activeTabIndex, false).then(() => { this.lazyLoadTabs(); this.ready = true; }); } } private lazyLoadTabs() { if (typeof this._activeTabIndex === 'undefined') { this.debug('lazyLoadTabs', 'called when _activeTabIndex is undefined'); return; } if (!this.config) { this.debug('lazyLoadTabs', 'called with no config available'); return; } const activeTab = this._activeTabIndex; const tabs = [...this.tabs]; if (!this.config!.lazyLoad) { for (const tab of this.tabs) { tab.loaded = true tab.visible = true } return; } const min = activeTab - 1; const max = activeTab + 1; let index = 0; for (const tab of tabs) { tab.visible = index >= min && index <= max; tab.loaded = tab.visible || (this.config!.unloadWhenInvisible ? false : tab.loaded); index++; } this.tabs = tabs; } private calcSelectedTab(): number { const scrollX = Math.max(0, Math.min(this.scrollWidth - this.width, this.el.scrollLeft)); return this.positionToIndex(scrollX); } private positionToIndex(scrollX: number) { const tabWidth = this.width; return scrollX / tabWidth; } private indexToPosition(tabIndex: number) { return Math.round(tabIndex * this.width * 10000) / 10000; } private normalizeSelectedTab(index: number): number { const scrollX = Math.max(0, Math.min(this.scrollWidth - this.width, this.indexToPosition(index))); return Math.round(scrollX / this.width); } /** * Internal method to output values in debug mode. */ private debug(...vals: any[]) { debugLog(this.config!, 'container', vals); } render() { return <slot></slot>; } }
the_stack
import BaseRemoteClient from "./BaseRemoteClient"; import ProjectServer from "./ProjectServer"; import { server as serverConfig } from "./config"; import * as path from "path"; import * as fs from "fs"; import * as rimraf from "rimraf"; import * as async from "async"; import * as recursiveReaddir from "recursive-readdir"; export default class RemoteProjectClient extends BaseRemoteClient { server: ProjectServer; id: string; constructor(server: ProjectServer, id: string, socket: SocketIO.Socket) { super(server, socket); this.id = id; this.socket.emit("welcome", this.id, { systemId: this.server.system.id, buildPort: serverConfig.buildPort, supportsServerBuild: this.server.system.serverBuild != null }); // Manifest this.socket.on("setProperty:manifest", this.onSetManifestProperty); // Entries this.socket.on("add:entries", this.onAddEntry); this.socket.on("duplicate:entries", this.onDuplicateEntry); this.socket.on("move:entries", this.onMoveEntry); this.socket.on("trash:entries", this.onTrashEntry); this.socket.on("setProperty:entries", this.onSetEntryProperty); this.socket.on("save:entries", this.onSaveEntry); // Assets this.socket.on("edit:assets", this.onEditAsset); this.socket.on("restore:assets", this.onRestoreAsset); this.socket.on("getRevision:assets", this.onGetAssetRevision); // Resources this.socket.on("edit:resources", this.onEditResource); // Rooms this.socket.on("edit:rooms", this.onEditRoom); // Project this.socket.on("vacuum:project", this.onVacuumProject); this.socket.on("build:project", this.onBuildProject); } // TODO: Implement roles and capabilities can(action: string) { return true; } // Manifest private onSetManifestProperty = (key: string, value: any, callback: (err: string, value: any) => any) => { this.server.data.manifest.setProperty(key, value, (err: string, actualValue: any) => { if (err != null) { callback(err, null); return; } this.server.io.in("sub:manifest").emit("setProperty:manifest", key, actualValue); callback(null, actualValue); }); } // Entries private onAddEntry = (name: string, type: string, options: any, callback: (err: string, newId?: string) => any) => { this.server.addEntry(this.socket.id, name, type, options, callback); } private onDuplicateEntry = (newName: string, originalEntryId: string, options: any, callback: (err: string, duplicatedId?: string) => any) => { this.server.duplicateEntry(this.socket.id, newName, originalEntryId, options, callback); } private onMoveEntry = (id: string, parentId: string, index: number, callback: (err: string) => any) => { this.server.moveEntry(this.socket.id, id, parentId, index, callback); } private onTrashEntry = (entryId: string, callback: (err: string) => any) => { this.server.trashEntry(this.socket.id, entryId, callback); } private onSetEntryProperty = (entryId: string, key: string, value: any, callback: (err: string) => any) => { if (key === "name") { this.server.renameEntry(this.socket.id, entryId, value, callback); return; } if (!this.errorIfCant("editAssets", callback)) return; if (value.indexOf("/") !== -1) { callback("Entry name cannot contain slashes"); return; } this.server.data.entries.setProperty(entryId, key, value, (err: string, actualValue: any) => { if (err != null) { callback(err); return; } this.server.io.in("sub:entries").emit("setProperty:entries", entryId, key, actualValue); callback(null); }); } private onSaveEntry = (entryId: string, revisionName: string, callback: (err: string) => void) => { this.server.saveEntry(this.socket.id, entryId, revisionName, callback); } // Assets private onEditAsset = (id: string, command: string, ...args: any[]) => { let callback: (err: string, id?: string) => any = null; if (typeof args[args.length - 1] === "function") callback = args.pop(); if (!this.errorIfCant("editAssets", callback)) return; const entry = this.server.data.entries.byId[id]; if (entry == null || entry.type == null) { callback("No such asset"); return; } if (command == null) { callback("Invalid command"); return; } const commandMethod = this.server.system.data.assetClasses[entry.type].prototype[`server_${command}`]; if (commandMethod == null) { callback("Invalid command"); return; } // if (callback == null) { this.server.log("Ignoring edit:assets command, missing a callback"); return; } this.server.data.assets.acquire(id, null, (err, asset) => { if (err != null) { callback("Could not acquire asset"); return; } commandMethod.call(asset, this, ...args, (err: string, ack: any, ...callbackArgs: any[]) => { this.server.data.assets.release(id, null); if (err != null) { callback(err); return; } this.server.io.in(`sub:assets:${id}`).emit("edit:assets", id, command, ...callbackArgs); callback(null, ack); }); }); } private onRestoreAsset = (assetId: string, revisionId: string, callback: (err: string) => void) => { const entry = this.server.data.entries.byId[assetId]; if (entry == null || entry.type == null) { callback("No such asset"); return; } const assetClass = this.server.system.data.assetClasses[entry.type]; const newAsset = new assetClass(assetId, null, this.server); const revisionName = this.server.data.entries.revisionsByEntryId[assetId][revisionId]; const revisionPath = `assetRevisions/${assetId}/${revisionId}-${revisionName}`; newAsset.load(path.join(this.server.projectPath, revisionPath)); newAsset.on("load", () => { this.server.data.assets.acquire(assetId, null, (err, asset) => { if (err != null) { callback("Could not acquire asset"); return; } this.server.data.assets.release(assetId, null); for (const badge of entry.badges) asset.emit("clearBadge", badge.id); entry.badges.length = 0; asset.pub = newAsset.pub; asset.setup(); asset.restore(); asset.emit("change"); this.server.io.in(`sub:assets:${assetId}`).emit("restore:assets", assetId, entry.type, asset.pub); callback(null); }); }); } private onGetAssetRevision = (assetId: string, revisionId: string, callback: (err: string, assetData?: any) => void) => { const entry = this.server.data.entries.byId[assetId]; if (entry == null || entry.type == null) { callback("No such asset"); return; } const assetClass = this.server.system.data.assetClasses[entry.type]; const revisionAsset = new assetClass(assetId, null, this.server); const revisionName = this.server.data.entries.revisionsByEntryId[assetId][revisionId]; const revisionPath = `assetRevisions/${assetId}/${revisionId}-${revisionName}`; revisionAsset.load(path.join(this.server.projectPath, revisionPath)); revisionAsset.on("load", () => { callback(null, revisionAsset.pub); }); } // Resources private onEditResource = (id: string, command: string, ...args: any[]) => { let callback: (err: string, id?: string) => any = null; if (typeof args[args.length - 1] === "function") callback = args.pop(); if (!this.errorIfCant("editResources", callback)) return; if (command == null) { callback("Invalid command"); return; } const commandMethod = this.server.system.data.resourceClasses[id].prototype[`server_${command}`]; if (commandMethod == null) { callback("Invalid command"); return; } // if (callback == null) { this.server.log("Ignoring edit:assets command, missing a callback"); return; } this.server.data.resources.acquire(id, null, (err, resource) => { if (err != null) { callback("Could not acquire resource"); return; } commandMethod.call(resource, this, ...args, (err: string, ack: any, ...callbackArgs: any[]) => { this.server.data.resources.release(id, null); if (err != null) { callback(err); return; } this.server.io.in(`sub:resources:${id}`).emit("edit:resources", id, command, ...callbackArgs); callback(null, ack); }); }); } // Rooms private onEditRoom = (id: string, command: string, ...args: any[]) => { let callback: (err: string, id?: string) => any = null; if (typeof args[args.length - 1] === "function") callback = args.pop(); if (!this.errorIfCant("editRooms", callback)) return; if (command == null) { callback("Invalid command"); return; } const commandMethod = (SupCore.Data.Room.prototype as any)[`server_${command}`]; if (commandMethod == null) { callback("Invalid command"); return; } // if (callback == null) { this.server.log("Ignoring edit:rooms command, missing a callback"); return; } this.server.data.rooms.acquire(id, null, (err, room) => { if (err != null) { callback("Could not acquire room"); return; } commandMethod.call(room, this, ...args, (err: string, ...callbackArgs: any[]) => { this.server.data.rooms.release(id, null); if (err != null) { callback(err); return; } this.server.io.in(`sub:rooms:${id}`).emit("edit:rooms", id, command, ...callbackArgs); callback(null, (callbackArgs[0] != null) ? callbackArgs[0].id : null); }); }); } // Project private onVacuumProject = (callback: (err: string, deletedCount?: number) => any) => { if (!this.errorIfCant("vacuumProject", callback)) return; const trashedAssetsPath = path.join(this.server.projectPath, "trashedAssets"); fs.readdir(trashedAssetsPath, (err, trashedAssetFolders) => { if (err != null) { if (err.code === "ENOENT") trashedAssetFolders = []; else throw err; } let removedFolderCount = 0; async.each(trashedAssetFolders, (trashedAssetFolder, cb) => { const folderPath = path.join(trashedAssetsPath, trashedAssetFolder); rimraf(folderPath, (err) => { if (err != null) SupCore.log(`Could not delete ${folderPath}.\n${(err as any).stack}`); else removedFolderCount++; cb(); }); }, () => { callback(null, removedFolderCount); }); }); } private onBuildProject = (callback: (err: string, buildId?: string, files?: string[]) => any) => { if (!this.errorIfCant("buildProject", callback)) return; // this.server.log("Building project..."); const buildId = this.server.nextBuildId; this.server.nextBuildId++; const buildPath = `${this.server.buildsPath}/${buildId}`; try { fs.mkdirSync(this.server.buildsPath); } catch (e) { /* Ignore */ } try { fs.mkdirSync(buildPath); } catch (err) { callback(`Could not create folder for build ${buildId}`); return; } this.server.system.serverBuild(this.server, buildPath, (err) => { if (err != null) { callback(`Failed to create build ${buildId}: ${err}`); return; } // Collect paths to all build files let files: string[] = []; recursiveReaddir(buildPath, (err, entries) => { for (const entry of entries) { let relativePath = path.relative(buildPath, entry); if (path.sep === "\\") relativePath = relativePath.replace(/\\/g, "/"); files.push(`/builds/${this.server.data.manifest.pub.id}/${buildId}/${relativePath}`); } callback(null, buildId.toString()); // Remove an old build to avoid using too much disk space const buildToDeleteId = buildId - serverConfig.maxRecentBuilds; const buildToDeletePath = `${this.server.buildsPath}/${buildToDeleteId}`; rimraf(buildToDeletePath, (err) => { if (err != null) { this.server.log(`Failed to remove build ${buildToDeleteId}:`); this.server.log(err.toString()); } }); }); }); } }
the_stack
import { Bifunctor3 } from 'fp-ts/Bifunctor' import { Alt3 } from 'fp-ts/Alt' import { Monad3 } from 'fp-ts/Monad' import { MonadTask3 } from 'fp-ts/MonadTask' import { MonadThrow3 } from 'fp-ts/MonadThrow' import { IncomingMessage } from 'http' import { Readable } from 'stream' import * as M from './Middleware' /** * Adapted from https://github.com/purescript-contrib/purescript-media-types * * @since 0.5.0 */ export const MediaType = { applicationFormURLEncoded: 'application/x-www-form-urlencoded', applicationJSON: 'application/json', applicationJavascript: 'application/javascript', applicationOctetStream: 'application/octet-stream', applicationXML: 'application/xml', imageGIF: 'image/gif', imageJPEG: 'image/jpeg', imagePNG: 'image/png', multipartFormData: 'multipart/form-data', textCSV: 'text/csv', textHTML: 'text/html', textPlain: 'text/plain', textXML: 'text/xml', } as const /** * @since 0.5.0 */ export type MediaType = typeof MediaType[keyof typeof MediaType] /** * @since 0.5.0 */ export const Status = { Continue: 100, SwitchingProtocols: 101, Processing: 102, EarlyHints: 103, OK: 200, Created: 201, Accepted: 202, NonAuthoritativeInformation: 203, NoContent: 204, ResetContent: 205, PartialContent: 206, MultiStatus: 207, AlreadyReported: 208, IMUsed: 226, MultipleChoices: 300, MovedPermanently: 301, Found: 302, SeeOther: 303, NotModified: 304, UseProxy: 305, SwitchProxy: 306, TemporaryRedirect: 307, PermanentRedirect: 308, BadRequest: 400, Unauthorized: 401, PaymentRequired: 402, Forbidden: 403, NotFound: 404, MethodNotAllowed: 405, NotAcceptable: 406, ProxyAuthenticationRequired: 407, RequestTimeout: 408, Conflict: 409, Gone: 410, LengthRequired: 411, PreconditionFailed: 412, PayloadTooLarge: 413, URITooLong: 414, UnsupportedMediaType: 415, RangeNotSatisfiable: 416, ExpectationFailed: 417, Teapot: 418, MisdirectedRequest: 421, UnprocessableEntity: 422, Locked: 423, FailedDependency: 424, TooEarly: 425, UpgradeRequired: 426, PreconditionRequired: 428, TooManyRequests: 429, RequestHeaderFieldsTooLarge: 431, UnavailableForLegalReasons: 451, InternalServerError: 500, NotImplemented: 501, BadGateway: 502, ServiceUnavailable: 503, GatewayTimeout: 504, HTTPVersionNotSupported: 505, VariantAlsoNegotiates: 506, InsufficientStorage: 507, LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511, } as const /** * @since 0.5.0 */ export type Status = typeof Status[keyof typeof Status] /** * @since 0.5.0 */ export interface CookieOptions { readonly expires?: Date readonly domain?: string readonly httpOnly?: boolean readonly maxAge?: number readonly path?: string readonly sameSite?: boolean | 'strict' | 'lax' readonly secure?: boolean readonly signed?: boolean } /** * Type indicating that the status-line is ready to be sent * * @since 0.5.0 */ export interface StatusOpen { readonly StatusOpen: unique symbol } /** * Type indicating that headers are ready to be sent, i.e. the body streaming has not been started * * @since 0.5.0 */ export interface HeadersOpen { readonly HeadersOpen: unique symbol } /** * Type indicating that headers have already been sent, and that the body is currently streaming * * @since 0.5.0 */ export interface BodyOpen { readonly BodyOpen: unique symbol } /** * Type indicating that headers have already been sent, and that the body stream, and thus the response, is finished * * @since 0.5.0 */ export interface ResponseEnded { readonly ResponseEnded: unique symbol } /** * A `Connection`, models the entirety of a connection between the HTTP server and the user agent, * both request and response. * State changes are tracked by the phantom type `S` * * @category model * @since 0.5.0 */ export interface Connection<S> { /** * @since 0.5.0 */ readonly _S: S readonly getRequest: () => IncomingMessage readonly getBody: () => unknown readonly getHeader: (name: string) => unknown readonly getParams: () => unknown readonly getQuery: () => unknown readonly getOriginalUrl: () => string readonly getMethod: () => string readonly setCookie: ( this: Connection<HeadersOpen>, name: string, value: string, options: CookieOptions ) => Connection<HeadersOpen> readonly clearCookie: (this: Connection<HeadersOpen>, name: string, options: CookieOptions) => Connection<HeadersOpen> readonly setHeader: (this: Connection<HeadersOpen>, name: string, value: string) => Connection<HeadersOpen> readonly setStatus: (this: Connection<StatusOpen>, status: Status) => Connection<HeadersOpen> readonly setBody: (this: Connection<BodyOpen>, body: unknown) => Connection<ResponseEnded> readonly pipeStream: (this: Connection<BodyOpen>, stream: Readable) => Connection<ResponseEnded> readonly endResponse: (this: Connection<BodyOpen>) => Connection<ResponseEnded> } /** * Use [`gets`](./Middleware.ts.html#gets) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const gets = M.gets /** * Use [`fromConnection`](./Middleware.ts.html#fromConnection) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const fromConnection = M.fromConnection /** * Use [`modifyConnection`](./Middleware.ts.html#modifyConnection) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const modifyConnection = M.modifyConnection /** * Use [`URI`](./Middleware.ts.html#uri) instead. * * @category instances * @since 0.5.0 * @deprecated */ export const URI = M.URI /** * Use [`URI`](./Middleware.ts.html#uri) instead. * * @category instances * @since 0.5.0 * @deprecated */ export type URI = typeof M.URI /** * Use [`Middleware`](./Middleware.ts.html#middleware) instead. * * @category model * @since 0.5.0 * @deprecated */ export type Middleware<I, O, E, A> = M.Middleware<I, O, E, A> /** * Use [`map`](./Middleware.ts.html#map) instead. * * @category Functor * @since 0.5.0 * @deprecated */ export const map = M.map /** * Use [`bimap`](./Middleware.ts.html#bimap) instead. * * @category Bifunctor * @since 0.6.3 * @deprecated */ export const bimap = M.bimap /** * Use [`mapLeft`](./Middleware.ts.html#mapLeft) instead. * * @category Bifunctor * @since 0.6.3 * @deprecated */ export const mapLeft = M.mapLeft /** * Use [`ap`](./Middleware.ts.html#ap) instead. * * @category Apply * @since 0.6.3 * @deprecated */ export const ap = M.ap /** * Use [`apW`](./Middleware.ts.html#apw) instead. * * @category Apply * @since 0.6.3 * @deprecated */ export const apW = M.apW /** * Use [`of`](./Middleware.ts.html#of) instead. * * @category Pointed * @since 0.6.3 * @deprecated */ export const of = M.of /** * Use [`iof`](./Middleware.ts.html#iof) instead. * * @category Pointed * @since 0.5.0 * @deprecated */ export const iof = M.iof /** * Use [`chain`](./Middleware.ts.html#chain) instead. * * @category Monad * @since 0.6.3 * @deprecated */ export const chain = M.chain /** * Use [`chainW`](./Middleware.ts.html#chainW) instead. * * @category Monad * @since 0.6.3 * @deprecated */ export const chainW = M.chainW /** * Use [`ichain`](./Middleware.ts.html#ichain) instead. * * @category Monad * @since 0.5.0 * @deprecated */ export const ichain = M.ichain /** * Use [`ichainW`](./Middleware.ts.html#ichainW) instead. * * @category Monad * @since 0.6.1 * @deprecated */ export const ichainW = M.ichainW /** * Use [`evalMiddleware`](./Middleware.ts.html#evalMiddleware) instead. * * @since 0.5.0 * @deprecated */ export const evalMiddleware = M.evalMiddleware /** * Use [`execMiddleware`](./Middleware.ts.html#execMiddleware) instead. * * @since 0.5.0 * @deprecated */ export const execMiddleware = M.execMiddleware /** * Use [`orElse`](./Middleware.ts.html#orelse) instead. * * @category combinators * @since 0.5.0 * @deprecated */ export const orElse = M.orElse /** * Use [`tryCatch`](./Middleware.ts.html#tryCatch) instead. * * @category interop * @since 0.5.0 * @deprecated */ export const tryCatch = M.tryCatch /** * Use [`fromTaskEither`](./Middleware.ts.html#fromTaskEither) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const fromTaskEither = M.fromTaskEither /** * Use [`right`](./Middleware.ts.html#right) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const right = M.right /** * Use [`left`](./Middleware.ts.html#left) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const left = M.left /** * Use [`rightTask`](./Middleware.ts.html#rightTask) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const rightTask = M.rightTask /** * Use [`leftTask`](./Middleware.ts.html#leftTask) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const leftTask = M.leftTask /** * Use [`rightIO`](./Middleware.ts.html#rightIO) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const rightIO = M.rightIO /** * Use [`leftIO`](./Middleware.ts.html#leftIO) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const leftIO = M.leftIO /** * Use [`fromIOEither`](./Middleware.ts.html#fromIOEither) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const fromIOEither = M.fromIOEither /** * Use [`status`](./Middleware.ts.html#status) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const status = M.status /** * Use [`header`](./Middleware.ts.html#header) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const header = M.header /** * Use [`contentType`](./Middleware.ts.html#contentType) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const contentType = M.contentType /** * Use [`cookie`](./Middleware.ts.html#cookie) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const cookie = M.cookie /** * Use [`clearCookie`](./Middleware.ts.html#clearCookie) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const clearCookie = M.clearCookie /** * Use [`closeHeaders`](./Middleware.ts.html#closeHeaders) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const closeHeaders = M.closeHeaders /** * Use [`send`](./Middleware.ts.html#send) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const send = M.send /** * Use [`end`](./Middleware.ts.html#end) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const end = M.end /** * Use [`json`](./Middleware.ts.html#json) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const json = M.json /** * Use [`redirect`](./Middleware.ts.html#redirect) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const redirect = M.redirect /** * Use [`pipeStream`](./Middleware.ts.html#pipeStream) instead. * * @category constructor * @since 0.6.2 * @deprecated */ export const pipeStream = M.pipeStream /** * Use [`decodeParam`](./Middleware.ts.html#decodeParam) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeParam = M.decodeParam /** * Use [`decodeParams`](./Middleware.ts.html#decodeParams) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeParams = M.decodeParams /** * Use [`decodeQuery`](./Middleware.ts.html#decodeQuery) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeQuery = M.decodeQuery /** * Use [`decodeBody`](./Middleware.ts.html#decodeBody) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeBody = M.decodeBody /** * Use [`decodeMethod`](./Middleware.ts.html#decodeMethod) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeMethod = M.decodeMethod /** * Use [`decodeHeader`](./Middleware.ts.html#decodeHeader) instead. * * @category constructor * @since 0.5.0 * @deprecated */ export const decodeHeader = M.decodeHeader /** * Use [`Do`](./Middleware.ts.html#do) instead. * * @since 0.6.1 * @deprecated */ // tslint:disable-next-line: deprecation export const Do = M.Do /** * Use [`bindTo`](./Middleware.ts.html#bindTo) instead. * * @since 0.6.1 * @deprecated */ export const bindTo = M.bindTo /** * Use [`bindW`](./Middleware.ts.html#bindW) instead. * * @since 0.6.1 * @deprecated */ export const bindW = M.bindW /** * Use [`bind`](./Middleware.ts.html#bind) instead. * * @since 0.6.1 * @deprecated */ export const bind = M.bind /** * Use smaller instances from [`Middleware`](./Middleware.ts.html) module instead. * * @category instances * @since 0.5.0 * @deprecated */ export const middleware: Monad3<M.URI> & Alt3<M.URI> & Bifunctor3<M.URI> & MonadThrow3<M.URI> & MonadTask3<M.URI> = { ...M.Functor, ...M.Bifunctor, ...M.MonadTask, ...M.MonadThrow, ...M.Alt, }
the_stack
import { visit } from 'jsonc-parser'; import { Injectable, Autowired } from '@opensumi/di'; import { PreferenceConfigurations, IContextKey, Emitter, Event, PreferenceService, URI, WaitUntilEvent, IContextKeyService, CommandService, localize, StorageProvider, STORAGE_NAMESPACE, IStorage, ThrottledDelayer, Deferred, } from '@opensumi/ide-core-browser'; import { WorkbenchEditorService, IOpenResourceResult } from '@opensumi/ide-editor'; import { IFileServiceClient } from '@opensumi/ide-file-service'; import { FileSystemError } from '@opensumi/ide-file-service'; import { ITextModel } from '@opensumi/ide-monaco/lib/browser/monaco-api/types'; import { QuickPickService } from '@opensumi/ide-quick-open'; import { IWorkspaceService } from '@opensumi/ide-workspace'; import { WorkspaceVariableContribution } from '@opensumi/ide-workspace/lib/browser/workspace-variable-contribution'; import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api'; import { DebugServer, IDebugServer, IDebuggerContribution, launchSchemaUri } from '../common'; import { DebugSessionOptions } from '../common'; import { DebugConfiguration } from '../common'; import { CONTEXT_DEBUGGERS_AVAILABLE } from './../common/constants'; import { DebugConfigurationModel } from './debug-configuration-model'; import { DebugPreferences } from './debug-preferences'; export type WillProvideDebugConfiguration = WaitUntilEvent; export type WillInitialConfiguration = WaitUntilEvent; export interface IDebugConfigurationData { current?: { name: string; workspaceFolderUri?: string; index: number; }; } @Injectable() export class DebugConfigurationManager { static DEFAULT_UPDATE_MODEL_TIMEOUT = 500; @Autowired(IWorkspaceService) protected readonly workspaceService: IWorkspaceService; @Autowired(WorkbenchEditorService) protected readonly workbenchEditorService: WorkbenchEditorService; @Autowired(IDebugServer) protected readonly debug: DebugServer; @Autowired(QuickPickService) protected readonly quickPick: QuickPickService; @Autowired(IContextKeyService) protected readonly contextKeyService: IContextKeyService; @Autowired(IFileServiceClient) protected readonly filesystem: IFileServiceClient; @Autowired(PreferenceService) protected readonly preferences: PreferenceService; @Autowired(PreferenceConfigurations) protected readonly preferenceConfigurations: PreferenceConfigurations; @Autowired(WorkspaceVariableContribution) protected readonly workspaceVariables: WorkspaceVariableContribution; @Autowired(StorageProvider) private readonly storageProvider: StorageProvider; @Autowired(CommandService) protected readonly commandService: CommandService; @Autowired(DebugPreferences) protected readonly debugPreferences: DebugPreferences; private contextDebuggersAvailable: IContextKey<boolean>; // 用于存储支持断点的语言 private breakpointModeIdsSet = new Set<string>(); // 用于存储debugger信息 private debuggers: IDebuggerContribution[] = []; protected readonly onDidChangeEmitter = new Emitter<void>(); readonly onDidChange: Event<void> = this.onDidChangeEmitter.event; protected readonly onWillProvideDebugConfigurationEmitter = new Emitter<WillProvideDebugConfiguration>(); readonly onWillProvideDebugConfiguration: Event<WillProvideDebugConfiguration> = this.onWillProvideDebugConfigurationEmitter.event; private _whenReadyDeferred: Deferred<void> = new Deferred(); protected updateModelDelayer: ThrottledDelayer<void> = new ThrottledDelayer( DebugConfigurationManager.DEFAULT_UPDATE_MODEL_TIMEOUT, ); private debugConfigurationStorage: IStorage; constructor() { this.init(); this.contextDebuggersAvailable = CONTEXT_DEBUGGERS_AVAILABLE.bind(this.contextKeyService); } protected async init(): Promise<void> { this.preferences.onPreferenceChanged((e) => { if (e.preferenceName === 'launch') { this.updateModels(); } }); this.debugConfigurationStorage = await this.storageProvider(STORAGE_NAMESPACE.DEBUG); this.updateModels(); } protected readonly models = new Map<string, DebugConfigurationModel>(); protected updateModels = () => this.updateModelDelayer.trigger(async () => { const roots = await this.workspaceService.roots; const toDelete = new Set(this.models.keys()); for (const rootStat of roots) { const key = rootStat.uri; toDelete.delete(key); if (!this.models.has(key)) { const model = new DebugConfigurationModel(key, this.preferences); model.onDidChange(() => this.updateCurrent()); model.onDispose(() => this.models.delete(key)); this.models.set(key, model); } } for (const uri of toDelete) { const model = this.models.get(uri); if (model) { model.dispose(); } } this.updateCurrent(); let configEmpty = true; this.models.forEach((model) => { if (model.configurations.length) { configEmpty = false; } }); this.contextDebuggersAvailable.set(!configEmpty); if (this._whenReadyDeferred) { this._whenReadyDeferred.resolve(); } }); get whenReady() { return this._whenReadyDeferred.promise; } get all(): DebugSessionOptions[] { return this.getAll(); } protected getAll(): DebugSessionOptions[] { const debugSessionOptions: DebugSessionOptions[] = []; for (const model of this.models.values()) { for (let index = 0, len = model.configurations.length; index < len; index++) { debugSessionOptions.push({ configuration: model.configurations[index], workspaceFolderUri: model.workspaceFolderUri, index, }); } } return debugSessionOptions; } get supported(): Promise<DebugSessionOptions[]> { return this.getSupported(); } protected async getSupported(): Promise<DebugSessionOptions[]> { await this.whenReady; const debugTypes = await this.debug.debugTypes(); return this.doGetSupported(new Set(debugTypes)); } protected doGetSupported(debugTypes: Set<string>): DebugSessionOptions[] { const supported: DebugSessionOptions[] = []; for (const options of this.getAll()) { if (debugTypes.has(options.configuration.type)) { supported.push(options); } } return supported; } protected _currentOptions: DebugSessionOptions | undefined; get current(): DebugSessionOptions | undefined { return this._currentOptions; } set current(option: DebugSessionOptions | undefined) { this.updateCurrent(option); } protected updateCurrent(options: DebugSessionOptions | undefined = this._currentOptions): void { this._currentOptions = options && this.find(options.configuration.name, options.workspaceFolderUri, options.index); if (!this._currentOptions) { const { model } = this; if (model) { const configuration = model.configurations[0]; if (configuration) { this._currentOptions = { configuration, workspaceFolderUri: model.workspaceFolderUri, index: options?.index || 0, }; } } } this.onDidChangeEmitter.fire(undefined); } find(name: string, workspaceFolderUri: string | undefined, index?: number): DebugSessionOptions | undefined { for (const model of this.models.values()) { if (model.workspaceFolderUri === workspaceFolderUri) { if (typeof index === 'number') { const configuration = model.configurations[index]; if (configuration && configuration.name === name) { return { configuration, workspaceFolderUri, index, }; } } else { // 兼容无index的查找逻辑 for (let index = 0, len = model.configurations.length; index < len; index++) { if (model.configurations[index].name === name) { return { configuration: model.configurations[index], workspaceFolderUri, index, }; } } } } } return undefined; } async openConfiguration(uri?: string): Promise<void> { let model: DebugConfigurationModel | undefined; if (uri) { model = this.getModelByUri(uri); } else { model = this.model; } if (model) { await this.doOpen(model); } } async addConfiguration(uri?: string): Promise<void> { let model: DebugConfigurationModel | undefined; if (uri) { model = this.getModelByUri(uri); } else { model = this.model; } if (!model) { return; } const resouce = await this.doOpen(model); if (!resouce) { return; } const { group } = resouce; const editor = group.codeEditor.monacoEditor; if (!editor) { return; } let position: monaco.Position | undefined; let depthInArray = 0; let lastProperty = ''; visit(editor.getValue(), { onObjectProperty: (property) => { lastProperty = property; }, onArrayBegin: (offset) => { if (lastProperty === 'configurations' && depthInArray === 0) { position = editor.getModel()!.getPositionAt(offset + 1); } depthInArray++; }, onArrayEnd: () => { depthInArray--; }, }); if (!position) { return; } // 判断在"configurations": [后是否有字符,如果有则新建一行 if (editor.getModel()!.getLineLastNonWhitespaceColumn(position.lineNumber) > position.column) { editor.setPosition(position); editor.trigger(launchSchemaUri, 'lineBreakInsert', undefined); } // 判断是否已有空行可用于插入建议,如果有,直接替换对应的光标位置 if (editor.getModel()!.getLineLastNonWhitespaceColumn(position.lineNumber + 1) === 0) { editor.setPosition({ lineNumber: position.lineNumber + 1, column: 1 << 30 }); editor.trigger(null, 'editor.action.deleteLines', []); } editor.setPosition(position); editor.trigger(null, 'editor.action.insertLineAfter', []); editor.trigger(null, 'editor.action.triggerSuggest', []); } protected get model(): DebugConfigurationModel | undefined { const workspaceFolderUri = this.workspaceVariables.getWorkspaceRootUri(); if (workspaceFolderUri) { const key = workspaceFolderUri.toString(); for (const model of this.models.values()) { if (model.workspaceFolderUri === key) { return model; } } } for (const model of this.models.values()) { if (model.uri) { return model; } } return this.models.values().next().value; } protected getModelByUri(uri: string): DebugConfigurationModel | undefined { if (uri) { const key = uri; for (const model of this.models.values()) { if (model.workspaceFolderUri === key) { return model; } } } for (const model of this.models.values()) { if (model.uri) { return model; } } return this.models.values().next().value; } protected async doOpen(model: DebugConfigurationModel): Promise<IOpenResourceResult> { let uri = model.uri; if (!uri) { uri = await this.doCreate(model); } return this.workbenchEditorService.open(uri, { disableNavigate: true, }); } protected async doCreate(model: DebugConfigurationModel): Promise<URI> { // 设置launch初始值 await this.preferences.set('launch', {}); // 获取可写入内容的文件 const { configUri } = this.preferences.resolve('launch'); let uri: URI; if (configUri && configUri.path.base === 'launch.json') { uri = configUri; } else { uri = new URI(model.workspaceFolderUri).resolve(`${this.preferenceConfigurations.getPaths()[0]}/launch.json`); } const debugType = await this.selectDebugType(); const configurations = debugType ? await this.provideDebugConfigurations(debugType, model.workspaceFolderUri) : []; const content = this.getInitialConfigurationContent(configurations); const fileStat = await this.filesystem.getFileStat(uri.toString()); if (!fileStat) { await this.filesystem.createFile(uri.toString(), { content, }); } else { try { await this.filesystem.setContent(fileStat, content); } catch (e) { if (!FileSystemError.FileExists.is(e)) { throw e; } } } return uri; } protected async provideDebugConfigurations( debugType: string, workspaceFolderUri: string | undefined, ): Promise<DebugConfiguration[]> { await this.fireWillProvideDebugConfiguration(); return this.debug.provideDebugConfigurations(debugType, workspaceFolderUri); } protected async fireWillProvideDebugConfiguration(): Promise<void> { await WaitUntilEvent.fire(this.onWillProvideDebugConfigurationEmitter, {}); } protected getInitialConfigurationContent(initialConfigurations: DebugConfiguration[]): string { const comment1 = localize('debug.configuration.comment1'); const comment2 = localize('debug.configuration.comment2'); const comment3 = localize('debug.configuration.comment3'); return `{ // ${comment1} // ${comment2} // ${comment3} "version": "0.2.0", "configurations": ${JSON.stringify(initialConfigurations, undefined, ' ') .split('\n') .map((line) => ' ' + line) .join('\n') .trim()} } `; } protected async selectDebugType(): Promise<string | undefined> { const editor = this.workbenchEditorService.currentEditor; if (!editor) { return undefined; } const document = editor.currentDocumentModel; if (!document) { return undefined; } const debuggers = await this.debug.getDebuggersForLanguage(document.languageId); return this.quickPick.show( debuggers.map(({ label, type }) => ({ label, value: type }), { placeholder: 'Select Environment' }), ); } async load(): Promise<void> { await this.whenReady; const data = this.debugConfigurationStorage.get<IDebugConfigurationData>('configurations'); if (data && data.current) { this.current = this.find(data.current.name, data.current.workspaceFolderUri, data.current.index); } } async save(): Promise<void> { const data: IDebugConfigurationData = {}; const { current } = this; if (current) { data.current = { name: current.configuration.name, workspaceFolderUri: current.workspaceFolderUri, index: current.index, }; } this.debugConfigurationStorage.set('configurations', data); } /** * 判断当前文档是否支持断点 * @param model */ canSetBreakpointsIn(model: ITextModel) { if (!model) { return false; } const modeId = (model as any).getLanguageIdentifier().language; if (!modeId || modeId === 'jsonc' || modeId === 'log') { // 不允许在JSONC类型文件及log文件中断点 return false; } if (this.debugPreferences['preference.debug.allowBreakpointsEverywhere']) { return true; } return this.breakpointModeIdsSet.has(modeId); } addSupportBreakpoints(languageId: string) { this.breakpointModeIdsSet.add(languageId); } removeSupportBreakpoints(languageId: string) { this.breakpointModeIdsSet.delete(languageId); } registerDebugger(debuggerContribution: IDebuggerContribution) { if (debuggerContribution.type !== '*') { const existing = this.getDebugger(debuggerContribution.type as string); if (existing) { // VSCode中会将插件贡献点根据isBuildIn进行覆盖式合并 return; } else { this.debuggers.push(debuggerContribution); } } } getDebugger(type: string): IDebuggerContribution | undefined { return this.debuggers.filter((dbg) => dbg.type === type).pop(); } getDebuggers(): IDebuggerContribution[] { return this.debuggers.filter((dbg) => !!dbg); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const QueryContext: msRest.CompositeMapper = { serializedName: "QueryContext", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "QueryContext", className: "QueryContext", modelProperties: { originalQuery: { required: true, serializedName: "originalQuery", type: { name: "String" } }, alteredQuery: { readOnly: true, serializedName: "alteredQuery", type: { name: "String" } }, alterationDisplayQuery: { readOnly: true, serializedName: "alterationDisplayQuery", type: { name: "String" } }, alterationOverrideQuery: { readOnly: true, serializedName: "alterationOverrideQuery", type: { name: "String" } }, adultIntent: { readOnly: true, serializedName: "adultIntent", type: { name: "Boolean" } }, askUserForLocation: { readOnly: true, serializedName: "askUserForLocation", type: { name: "Boolean" } }, isTransactional: { readOnly: true, serializedName: "isTransactional", type: { name: "Boolean" } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const EntitiesEntityPresentationInfo: msRest.CompositeMapper = { serializedName: "Entities/EntityPresentationInfo", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "EntitiesEntityPresentationInfo", className: "EntitiesEntityPresentationInfo", modelProperties: { entityScenario: { required: true, serializedName: "entityScenario", defaultValue: 'DominantEntity', type: { name: "String" } }, entityTypeHints: { readOnly: true, serializedName: "entityTypeHints", type: { name: "Sequence", element: { type: { name: "String" } } } }, entityTypeDisplayHint: { readOnly: true, serializedName: "entityTypeDisplayHint", type: { name: "String" } }, query: { readOnly: true, serializedName: "query", type: { name: "String" } }, entitySubTypeHints: { readOnly: true, serializedName: "entitySubTypeHints", type: { name: "Sequence", element: { type: { name: "String" } } } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const ResponseBase: msRest.CompositeMapper = { serializedName: "ResponseBase", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "ResponseBase", className: "ResponseBase", modelProperties: { _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const Identifiable: msRest.CompositeMapper = { serializedName: "Identifiable", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Identifiable", modelProperties: { ...ResponseBase.type.modelProperties, id: { readOnly: true, serializedName: "id", type: { name: "String" } } } } }; export const Response: msRest.CompositeMapper = { serializedName: "Response", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Response", modelProperties: { ...Identifiable.type.modelProperties, readLink: { readOnly: true, serializedName: "readLink", type: { name: "String" } }, webSearchUrl: { readOnly: true, serializedName: "webSearchUrl", type: { name: "String" } }, potentialAction: { readOnly: true, serializedName: "potentialAction", type: { name: "Sequence", element: { type: { name: "Composite", className: "Action" } } } }, immediateAction: { readOnly: true, serializedName: "immediateAction", type: { name: "Sequence", element: { type: { name: "Composite", className: "Action" } } } }, preferredClickthroughUrl: { readOnly: true, serializedName: "preferredClickthroughUrl", type: { name: "String" } }, adaptiveCard: { readOnly: true, serializedName: "adaptiveCard", type: { name: "String" } } } } }; export const Thing: msRest.CompositeMapper = { serializedName: "Thing", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Thing", modelProperties: { ...Response.type.modelProperties, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, url: { readOnly: true, serializedName: "url", type: { name: "String" } }, entityPresentationInfo: { readOnly: true, serializedName: "entityPresentationInfo", type: { name: "Composite", className: "EntitiesEntityPresentationInfo" } } } } }; export const Answer: msRest.CompositeMapper = { serializedName: "Answer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Answer", modelProperties: { ...Response.type.modelProperties } } }; export const SearchResultsAnswer: msRest.CompositeMapper = { serializedName: "SearchResultsAnswer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchResultsAnswer", modelProperties: { ...Answer.type.modelProperties, queryContext: { readOnly: true, serializedName: "queryContext", type: { name: "Composite", className: "QueryContext" } }, totalEstimatedMatches: { readOnly: true, serializedName: "totalEstimatedMatches", type: { name: "Number" } }, isFamilyFriendly: { readOnly: true, serializedName: "isFamilyFriendly", type: { name: "Boolean" } } } } }; export const Places: msRest.CompositeMapper = { serializedName: "Places", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Places", modelProperties: { ...SearchResultsAnswer.type.modelProperties, value: { required: true, serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } } } } }; export const SearchResponse: msRest.CompositeMapper = { serializedName: "SearchResponse", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchResponse", modelProperties: { ...Response.type.modelProperties, queryContext: { readOnly: true, serializedName: "queryContext", type: { name: "Composite", className: "QueryContext" } }, places: { readOnly: true, serializedName: "places", type: { name: "Composite", className: "Places" } }, lottery: { readOnly: true, serializedName: "lottery", type: { name: "Composite", className: "SearchResultsAnswer" } }, searchResultsConfidenceScore: { readOnly: true, serializedName: "searchResultsConfidenceScore", type: { name: "Number" } } } } }; export const GeoCoordinates: msRest.CompositeMapper = { serializedName: "GeoCoordinates", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "GeoCoordinates", className: "GeoCoordinates", modelProperties: { latitude: { required: true, serializedName: "latitude", type: { name: "Number" } }, longitude: { required: true, serializedName: "longitude", type: { name: "Number" } }, elevation: { readOnly: true, serializedName: "elevation", type: { name: "Number" } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const Intangible: msRest.CompositeMapper = { serializedName: "Intangible", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Intangible", modelProperties: { ...Thing.type.modelProperties } } }; export const StructuredValue: msRest.CompositeMapper = { serializedName: "StructuredValue", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "StructuredValue", modelProperties: { ...Intangible.type.modelProperties } } }; export const PostalAddress: msRest.CompositeMapper = { serializedName: "PostalAddress", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "PostalAddress", modelProperties: { ...StructuredValue.type.modelProperties, streetAddress: { readOnly: true, serializedName: "streetAddress", type: { name: "String" } }, addressLocality: { readOnly: true, serializedName: "addressLocality", type: { name: "String" } }, addressSubregion: { readOnly: true, serializedName: "addressSubregion", type: { name: "String" } }, addressRegion: { readOnly: true, serializedName: "addressRegion", type: { name: "String" } }, postalCode: { readOnly: true, serializedName: "postalCode", type: { name: "String" } }, postOfficeBoxNumber: { readOnly: true, serializedName: "postOfficeBoxNumber", type: { name: "String" } }, addressCountry: { readOnly: true, serializedName: "addressCountry", type: { name: "String" } }, countryIso: { readOnly: true, serializedName: "countryIso", type: { name: "String" } }, neighborhood: { readOnly: true, serializedName: "neighborhood", type: { name: "String" } }, addressRegionAbbreviation: { readOnly: true, serializedName: "addressRegionAbbreviation", type: { name: "String" } }, text: { readOnly: true, serializedName: "text", type: { name: "String" } }, houseNumber: { readOnly: true, serializedName: "houseNumber", type: { name: "String" } }, streetName: { readOnly: true, serializedName: "streetName", type: { name: "String" } }, formattingRuleId: { readOnly: true, serializedName: "formattingRuleId", type: { name: "String" } } } } }; export const Place: msRest.CompositeMapper = { serializedName: "Place", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Place", modelProperties: { ...Thing.type.modelProperties, geo: { readOnly: true, serializedName: "geo", type: { name: "Composite", className: "GeoCoordinates" } }, routablePoint: { readOnly: true, serializedName: "routablePoint", type: { name: "Composite", className: "GeoCoordinates" } }, address: { readOnly: true, serializedName: "address", type: { name: "Composite", className: "PostalAddress" } }, telephone: { readOnly: true, serializedName: "telephone", type: { name: "String" } } } } }; export const CreativeWork: msRest.CompositeMapper = { serializedName: "CreativeWork", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "CreativeWork", modelProperties: { ...Thing.type.modelProperties, thumbnailUrl: { readOnly: true, serializedName: "thumbnailUrl", type: { name: "String" } }, about: { readOnly: true, serializedName: "about", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, mentions: { readOnly: true, serializedName: "mentions", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, provider: { readOnly: true, serializedName: "provider", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, creator: { readOnly: true, serializedName: "creator", type: { name: "Composite", className: "Thing" } }, text: { readOnly: true, serializedName: "text", type: { name: "String" } }, discussionUrl: { readOnly: true, serializedName: "discussionUrl", type: { name: "String" } }, commentCount: { readOnly: true, serializedName: "commentCount", type: { name: "Number" } }, mainEntity: { readOnly: true, serializedName: "mainEntity", type: { name: "Composite", className: "Thing" } }, headLine: { readOnly: true, serializedName: "headLine", type: { name: "String" } }, copyrightHolder: { readOnly: true, serializedName: "copyrightHolder", type: { name: "Composite", className: "Thing" } }, copyrightYear: { readOnly: true, serializedName: "copyrightYear", type: { name: "Number" } }, disclaimer: { readOnly: true, serializedName: "disclaimer", type: { name: "String" } }, isAccessibleForFree: { readOnly: true, serializedName: "isAccessibleForFree", type: { name: "Boolean" } }, genre: { readOnly: true, serializedName: "genre", type: { name: "Sequence", element: { type: { name: "String" } } } }, isFamilyFriendly: { readOnly: true, serializedName: "isFamilyFriendly", type: { name: "Boolean" } } } } }; export const Action: msRest.CompositeMapper = { serializedName: "Action", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Action", modelProperties: { ...CreativeWork.type.modelProperties, location: { readOnly: true, serializedName: "location", type: { name: "Sequence", element: { type: { name: "Composite", className: "Place" } } } }, result: { readOnly: true, serializedName: "result", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, displayName: { readOnly: true, serializedName: "displayName", type: { name: "String" } }, isTopAction: { readOnly: true, serializedName: "isTopAction", type: { name: "Boolean" } }, serviceUrl: { readOnly: true, serializedName: "serviceUrl", type: { name: "String" } } } } }; export const ErrorModel: msRest.CompositeMapper = { serializedName: "Error", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "ErrorModel", className: "ErrorModel", modelProperties: { code: { required: true, serializedName: "code", defaultValue: 'None', type: { name: "String" } }, subCode: { readOnly: true, serializedName: "subCode", type: { name: "String" } }, message: { required: true, serializedName: "message", type: { name: "String" } }, moreDetails: { readOnly: true, serializedName: "moreDetails", type: { name: "String" } }, parameter: { readOnly: true, serializedName: "parameter", type: { name: "String" } }, value: { readOnly: true, serializedName: "value", type: { name: "String" } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "ErrorResponse", modelProperties: { ...Response.type.modelProperties, errors: { required: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorModel" } } } } } } }; export const SearchAction: msRest.CompositeMapper = { serializedName: "SearchAction", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchAction", modelProperties: { ...Action.type.modelProperties, displayText: { readOnly: true, serializedName: "displayText", type: { name: "String" } }, query: { readOnly: true, serializedName: "query", type: { name: "String" } }, richContent: { readOnly: true, serializedName: "richContent", type: { name: "Sequence", element: { type: { name: "Composite", className: "Answer" } } } }, formattingRuleId: { readOnly: true, serializedName: "formattingRuleId", type: { name: "String" } } } } }; export const discriminators = { 'QueryContext' : QueryContext, 'Entities/EntityPresentationInfo' : EntitiesEntityPresentationInfo, 'ResponseBase.Thing' : Thing, 'ResponseBase.Places' : Places, 'ResponseBase.SearchResultsAnswer' : SearchResultsAnswer, 'ResponseBase.SearchResponse' : SearchResponse, 'GeoCoordinates' : GeoCoordinates, 'ResponseBase.PostalAddress' : PostalAddress, 'ResponseBase.Place' : Place, 'ResponseBase.Action' : Action, 'ResponseBase.Response' : Response, 'ResponseBase.Identifiable' : Identifiable, 'ResponseBase.Answer' : Answer, 'Error' : ErrorModel, 'ResponseBase.ErrorResponse' : ErrorResponse, 'ResponseBase.CreativeWork' : CreativeWork, 'ResponseBase' : ResponseBase, 'ResponseBase.Intangible' : Intangible, 'ResponseBase.SearchAction' : SearchAction, 'ResponseBase.StructuredValue' : StructuredValue };
the_stack
import cloneDeep from 'lodash/cloneDeep'; import { AppConstants } from 'app.constants'; import { AnswerGroup, AnswerGroupObjectFactory } from 'domain/exploration/AnswerGroupObjectFactory'; import { FractionInputValidationService } from 'interactions/FractionInput/directives/fraction-input-validation.service'; import { Outcome, OutcomeObjectFactory } from 'domain/exploration/OutcomeObjectFactory'; import { Rule, RuleObjectFactory } from 'domain/exploration/RuleObjectFactory'; import { TestBed } from '@angular/core/testing'; import { FractionInputCustomizationArgs } from 'interactions/customization-args-defs'; import { FractionDict } from 'domain/objects/fraction.model'; import { SubtitledUnicode } from 'domain/exploration/SubtitledUnicodeObjectFactory'; describe('FractionInputValidationService', () => { let validatorService: FractionInputValidationService; let WARNING_TYPES: typeof AppConstants.WARNING_TYPES; let currentState: string; let answerGroups: AnswerGroup[]; let goodDefaultOutcome: Outcome; let customizationArgs: FractionInputCustomizationArgs; let denominatorEqualsFiveRule: Rule, equalsOneAndHalfRule: Rule, equalsOneRule: Rule, equalsThreeByTwoRule: Rule, equivalentToOneAndSimplestFormRule: Rule, equivalentToOneRule: Rule, exactlyEqualToOneAndNotInSimplestFormRule: Rule, HasFractionalPartExactlyEqualToOneAndHalfRule: Rule, HasFractionalPartExactlyEqualToNegativeValue: Rule, HasFractionalPartExactlyEqualToThreeHalfs: Rule, HasFractionalPartExactlyEqualToTwoFifthsRule: Rule, HasNoFractionalPart: Rule, greaterThanMinusOneRule: Rule, integerPartEqualsOne: Rule, integerPartEqualsZero: Rule, lessThanTwoRule: Rule, nonIntegerRule: Rule, numeratorEqualsFiveRule: Rule, zeroDenominatorRule: Rule; let createFractionDict: ( isNegative: boolean, wholeNumber: number, numerator: number, denominator: number) => FractionDict; let oof: OutcomeObjectFactory; let agof: AnswerGroupObjectFactory; let rof: RuleObjectFactory; beforeEach(() => { validatorService = TestBed.inject(FractionInputValidationService); oof = TestBed.inject(OutcomeObjectFactory); agof = TestBed.inject(AnswerGroupObjectFactory); rof = TestBed.inject(RuleObjectFactory); WARNING_TYPES = AppConstants.WARNING_TYPES; createFractionDict = ( isNegative: boolean, wholeNumber: number, numerator: number, denominator: number): FractionDict => { return { isNegative: isNegative, wholeNumber: wholeNumber, numerator: numerator, denominator: denominator }; }; customizationArgs = { requireSimplestForm: { value: true }, allowImproperFraction: { value: true }, allowNonzeroIntegerPart: { value: true }, customPlaceholder: { value: new SubtitledUnicode('', '') } }; currentState = 'First State'; goodDefaultOutcome = oof.createFromBackendDict({ dest: 'Second State', feedback: { html: '', content_id: '' }, labelled_as_correct: false, param_changes: [], refresher_exploration_id: null, missing_prerequisite_skill_id: null }); equalsOneRule = rof.createFromBackendDict({ rule_type: 'IsExactlyEqualTo', inputs: { f: createFractionDict(false, 0, 1, 1) } }, 'FractionInput'); equalsThreeByTwoRule = rof.createFromBackendDict({ rule_type: 'IsExactlyEqualTo', inputs: { f: createFractionDict(false, 0, 3, 2) } }, 'FractionInput'); equalsOneAndHalfRule = rof.createFromBackendDict({ rule_type: 'IsExactlyEqualTo', inputs: { f: createFractionDict(false, 1, 1, 2) } }, 'FractionInput'); greaterThanMinusOneRule = rof.createFromBackendDict({ rule_type: 'IsGreaterThan', inputs: { f: createFractionDict(true, 0, 1, 1) } }, 'FractionInput'); integerPartEqualsOne = rof.createFromBackendDict({ rule_type: 'HasIntegerPartEqualTo', inputs: { x: 1 } }, 'FractionInput'); integerPartEqualsZero = rof.createFromBackendDict({ rule_type: 'HasIntegerPartEqualTo', inputs: { x: 0 } }, 'FractionInput'); lessThanTwoRule = rof.createFromBackendDict({ rule_type: 'IsLessThan', inputs: { f: createFractionDict(false, 0, 2, 1) } }, 'FractionInput'); equivalentToOneRule = rof.createFromBackendDict({ rule_type: 'IsEquivalentTo', inputs: { f: createFractionDict(false, 0, 10, 10) } }, 'FractionInput'); equivalentToOneAndSimplestFormRule = rof.createFromBackendDict({ rule_type: 'IsEquivalentToAndInSimplestForm', inputs: { f: createFractionDict(false, 0, 10, 10) } }, 'FractionInput'); exactlyEqualToOneAndNotInSimplestFormRule = rof.createFromBackendDict({ rule_type: 'IsExactlyEqualTo', inputs: { f: createFractionDict(false, 0, 10, 10) } }, 'FractionInput'); nonIntegerRule = rof.createFromBackendDict({ rule_type: 'HasNumeratorEqualTo', inputs: { x: 0.5 } }, 'FractionInput'); zeroDenominatorRule = rof.createFromBackendDict({ rule_type: 'HasDenominatorEqualTo', inputs: { x: 0 } }, 'FractionInput'); numeratorEqualsFiveRule = rof.createFromBackendDict({ rule_type: 'HasNumeratorEqualTo', inputs: { x: 5 } }, 'FractionInput'); denominatorEqualsFiveRule = rof.createFromBackendDict({ rule_type: 'HasDenominatorEqualTo', inputs: { x: 5 } }, 'FractionInput'); HasFractionalPartExactlyEqualToTwoFifthsRule = rof.createFromBackendDict({ rule_type: 'HasFractionalPartExactlyEqualTo', inputs: { f: createFractionDict(false, 0, 2, 5) } }, 'FractionInput'); HasFractionalPartExactlyEqualToOneAndHalfRule = rof.createFromBackendDict({ rule_type: 'HasFractionalPartExactlyEqualTo', inputs: { f: createFractionDict(false, 1, 1, 2) } }, 'FractionInput'); HasFractionalPartExactlyEqualToNegativeValue = rof.createFromBackendDict({ rule_type: 'HasFractionalPartExactlyEqualTo', inputs: { f: createFractionDict(true, 0, 1, 2) } }, 'FractionInput'); HasFractionalPartExactlyEqualToThreeHalfs = rof.createFromBackendDict({ rule_type: 'HasFractionalPartExactlyEqualTo', inputs: { f: createFractionDict(false, 0, 3, 2) } }, 'FractionInput'); HasNoFractionalPart = rof.createFromBackendDict({ rule_type: 'HasNoFractionalPart', inputs: { f: createFractionDict(false, 2, 0, 1) } }, 'FractionInput'); answerGroups = [agof.createNew( [equalsOneRule, lessThanTwoRule], goodDefaultOutcome, [], null )]; }); it('should be able to perform basic validation', function() { var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should catch redundant rules', function() { answerGroups[0].rules = [lessThanTwoRule, equalsOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 2 from answer group 1 will never be matched ' + 'because it is made redundant by rule 1 from answer group 1.' }]); }); it('should not catch equals followed by equivalent as redundant', function() { answerGroups[0].rules = [equalsOneRule, equivalentToOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); answerGroups[0].rules = [equalsOneRule, equivalentToOneAndSimplestFormRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should catch equivalent followed by equals same value' + 'as redundant', function() { answerGroups[0].rules = [equivalentToOneRule, equalsOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 2 from answer group 1 will never be matched ' + 'because it is made redundant by rule 1 from answer group 1.' }]); answerGroups[0].rules = [equivalentToOneAndSimplestFormRule, equalsOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 2 from answer group 1 will never be matched ' + 'because it is made redundant by rule 1 from answer group 1.' }]); }); it('should catch redundant rules in separate answer groups', () => { answerGroups[1] = cloneDeep(answerGroups[0]); answerGroups[0].rules = [greaterThanMinusOneRule]; answerGroups[1].rules = [equalsOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 1 from answer group 2 will never be matched ' + 'because it is made redundant by rule 1 from answer group 1.' }]); }); it('should catch redundant rules caused by greater/less than range', () => { answerGroups[0].rules = [greaterThanMinusOneRule, equalsOneRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 2 from answer group 1 will never be matched ' + 'because it is made redundant by rule 1 from answer group 1.' }]); }); it('should catch redundant rules caused by exactly equals', () => { answerGroups[0].rules = [exactlyEqualToOneAndNotInSimplestFormRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: 'Rule 1 from answer group 1 will never be matched ' + 'because it is not in simplest form.' }]); }); it('should catch non integer inputs in the numerator', () => { answerGroups[0].rules = [nonIntegerRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' is invalid: input should be an ' + 'integer.') }]); }); it('should catch non integer inputs in the whole number', () => { nonIntegerRule.type = 'HasIntegerPartEqualTo'; answerGroups[0].rules = [nonIntegerRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' is invalid: input should be an ' + 'integer.') }]); }); it('should catch non integer inputs in the denominator', () => { nonIntegerRule.type = 'HasDenominatorEqualTo'; answerGroups[0].rules = [nonIntegerRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' is invalid: input should be an ' + 'integer.') }]); }); it('should catch zero input in denominator', () => { answerGroups[0].rules = [zeroDenominatorRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' is invalid: denominator should be ' + 'greater than zero.') }]); }); it('should catch not allowImproperFraction and rule has improper fraction', () => { customizationArgs.allowImproperFraction.value = false; answerGroups[0].rules = [equalsThreeByTwoRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' will never be matched because it is an ' + 'improper fraction') }]); }); it('should catch not allowNonzeroIntegerPart and rule has integer part', () => { customizationArgs.allowNonzeroIntegerPart.value = false; answerGroups[0].rules = [equalsOneAndHalfRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' will never be matched because it has a ' + 'non zero integer part') }]); }); it('should not catch anything when there is no fractional part', () => { customizationArgs.allowNonzeroIntegerPart.value = false; answerGroups[0].rules = [HasNoFractionalPart]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should catch if not allowNonzeroIntegerPart and ' + 'rule is HasIntegerPartEqualTo a non zero value', () => { customizationArgs.allowNonzeroIntegerPart.value = false; answerGroups[0].rules = [integerPartEqualsOne]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule ' + 1 + ' from answer group ' + 1 + ' will never be matched because integer part ' + 'has to be zero') }]); }); it('should allow if not allowNonzeroIntegerPart and ' + 'rule is HasIntegerPartEqualTo a zero value', () => { customizationArgs.allowNonzeroIntegerPart.value = false; answerGroups[0].rules = [integerPartEqualsZero]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should allow equivalent fractions with if not requireSimplestForm ' + 'and rules are IsExactlyEqualTo', () => { customizationArgs.requireSimplestForm.value = false; answerGroups[1] = cloneDeep(answerGroups[0]); answerGroups[0].rules = [equalsOneRule]; answerGroups[1].rules = [exactlyEqualToOneAndNotInSimplestFormRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should allow if numerator and denominator should equal the same value ' + 'and are set in different rules', () => { customizationArgs.requireSimplestForm.value = false; answerGroups[1] = cloneDeep(answerGroups[0]); answerGroups[0].rules = [numeratorEqualsFiveRule]; answerGroups[1].rules = [denominatorEqualsFiveRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); }); it('should correctly check validity of HasFractionalPartExactlyEqualTo rule', () => { customizationArgs.requireSimplestForm.value = false; answerGroups[0].rules = [HasFractionalPartExactlyEqualToOneAndHalfRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule 1 from answer group 1 is invalid as ' + 'integer part should be zero') }]); customizationArgs.allowImproperFraction.value = false; answerGroups[0].rules = [HasFractionalPartExactlyEqualToThreeHalfs]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule 1 from answer group 1 is invalid as ' + 'improper fractions are not allowed') }]); answerGroups[0].rules = [HasFractionalPartExactlyEqualToNegativeValue]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule 1 from answer group 1 is invalid as ' + 'sign should be positive') }]); customizationArgs.allowImproperFraction.value = true; answerGroups[0].rules = [HasFractionalPartExactlyEqualToTwoFifthsRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([]); answerGroups[1] = cloneDeep(answerGroups[0]); answerGroups[0].rules = [denominatorEqualsFiveRule]; answerGroups[1].rules = [HasFractionalPartExactlyEqualToTwoFifthsRule]; var warnings = validatorService.getAllWarnings( currentState, customizationArgs, answerGroups, goodDefaultOutcome); expect(warnings).toEqual([{ type: WARNING_TYPES.ERROR, message: ( 'Rule 1 from answer group 2 will never be matched because it ' + 'is made redundant by rule 1 from answer group 1.') }]); }); });
the_stack
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {User} from '@domain/user/user'; import {UserService} from '../service/user.service'; import {CookieConstant} from '@common/constant/cookie.constant'; import {AbstractComponent} from '@common/component/abstract.component'; import {JoinComponent} from './component/join/join.component'; import {ResetPasswordComponent} from './component/reset-password/reset-password.component'; import {Alert} from '@common/util/alert.util'; import {ActivatedRoute} from '@angular/router'; import {WorkspaceService} from '../../workspace/service/workspace.service'; import {PermissionService} from '../service/permission.service'; import {ConfirmSmallComponent} from '@common/component/modal/confirm-small/confirm-small.component'; import {Modal} from '@common/domain/modal'; import {CommonUtil} from '@common/util/common.util'; import {InitialChangePasswordComponent} from './component/initial-change-password/initial-change-password.component'; declare let moment: any; @Component({ selector: 'app-login', templateUrl: './login.component.html', }) export class LoginComponent extends AbstractComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private forwardURL: string; // 사용자 신청 팝업 컴포넌트 @ViewChild(JoinComponent) private joinComponent: JoinComponent; // 비밀번호 변경 팝업 컴포넌트 @ViewChild(ResetPasswordComponent) private resetPasswordComponent: ResetPasswordComponent; // 확인 팝업 컴포넌트 @ViewChild(ConfirmSmallComponent) private _confirmModal: ConfirmSmallComponent; @ViewChild(InitialChangePasswordComponent) private initialChangePasswordComponent: InitialChangePasswordComponent; @ViewChild('pwElm') private _pwElm: ElementRef; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 유저 엔티티 public user: User = new User(); // 아이디 기억 여부 public isRemember: boolean = false; // 이용약관 표시 여부 public isShowTerms: boolean = false; public loginFailMsg: string; public useCancelBtn: boolean = false; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor(private userService: UserService, private workspaceService: WorkspaceService, private permissionService: PermissionService, private activatedRoute: ActivatedRoute, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } ngOnInit() { super.ngOnInit(); localStorage.removeItem('USE_SAML_SSO'); this.activatedRoute.queryParams.subscribe((params) => { this.forwardURL = params['forwardURL'] || 'NONE'; }); // this.user.username = 'admin'; // this.user.password = 'admin'; const id = this.cookieService.get(CookieConstant.KEY.SAVE_USER_ID); if (id) { this.isRemember = true; this.user.username = id; } if (this.cookieService.get(CookieConstant.KEY.LOGIN_TOKEN) !== '') { if (this.forwardURL !== 'NONE') { this.router.navigate([this.forwardURL]).then(); } else { this.router.navigate(['/workspace']).then(); } } } ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 사용자 신청하기 public join() { this.joinComponent.init(); } // 사용자 신청 완료 public joinComplete(data: { code: string, msg?: string }) { // modal const modal = new Modal(); if ('SUCCESS' === data.code) { // message modal.name = this.translateService.instant('msg.login.join.title'); modal.description = this.translateService.instant('msg.login.join.cmplt.description'); modal.subDescription = this.translateService.instant('msg.login.join.cmplt.description2'); } else { modal.name = this.translateService.instant('login.join.fail'); ('' !== data.msg) && (modal.description = data.msg); } // confirm modal this.useCancelBtn = false; this._confirmModal.init(modal); // this.joinCompleteComponent.init(); } public confirmComplete(data) { if (!CommonUtil.isNullOrUndefined(data)) { if (data === this.user) { this.login(); } else { this.router.navigate([data]).then(); } } } // 비밀번호 찾기 public resetPassword() { this.resetPasswordComponent.init(); } public checkIp() { if (this._confirmModal.isShow) { return; } this.loadingShow(); (this.user.username) && (this.user.username = this.user.username.trim()); this.userService.checkUserIp(this.user).then((host) => { if (host === true) { this.login(); } else { this.loadingHide(); const modal = new Modal(); modal.name = this.translateService.instant('msg.login.access.title'); modal.description = this.translateService.instant('msg.sso.ui.confirm.userip', {value: host}); modal.data = this.user; // confirm modal this.useCancelBtn = true; this._confirmModal.init(modal); } }).catch(() => { this._logout(); Alert.error(this.translateService.instant('login.ui.failed'), true); this.loadingHide(); }); } /** * 로그인 */ public login() { if (this._confirmModal.isShow) { return; } this.loadingShow(); (this.user.username) && (this.user.username = this.user.username.trim()); this.loginFailMsg = ''; this.userService.login(this.user).then((loginToken) => { if (loginToken.access_token) { // 쿠키 저장 this.cookieService.set(CookieConstant.KEY.LOGIN_TOKEN, loginToken.access_token, 0, '/'); this.cookieService.set(CookieConstant.KEY.LOGIN_TOKEN_TYPE, loginToken.token_type, 0, '/'); this.cookieService.set(CookieConstant.KEY.REFRESH_LOGIN_TOKEN, loginToken.refresh_token, 0, '/'); this.cookieService.set(CookieConstant.KEY.LOGIN_USER_ID, this.user.username, 0, '/'); if (this.isRemember) { this.cookieService.set(CookieConstant.KEY.SAVE_USER_ID, this.user.username, 0, '/'); } else { this.cookieService.delete(CookieConstant.KEY.SAVE_USER_ID, '/'); } // 유저 권한 조회 this.permissionService.getPermissions('SYSTEM').then((permission) => { if (permission && 0 < permission.length) { this.cookieService.set(CookieConstant.KEY.PERMISSION, permission.join('=='), 0, '/'); // 내 워크스페이스 정보 조회 this.workspaceService.getMyWorkspace().then(wsInfo => { // 내 워크스페이스 정보 저장 this.cookieService.set(CookieConstant.KEY.MY_WORKSPACE, JSON.stringify(wsInfo), 0, '/'); // 페이지 이동 if (this.forwardURL !== 'NONE') { // this.router.navigate([this.forwardURL]).then(); this._showAccessLog(loginToken.last_login_time, loginToken.last_login_ip, this.forwardURL); } else { // this.router.navigate(['/workspace']).then(); this._showAccessLog(loginToken.last_login_time, loginToken.last_login_ip, '/workspace'); } }).catch(() => { this._logout(); Alert.error(this.translateService.instant('login.ui.failed'), true); this.loadingHide(); }); } else { // this.router.navigate(['/workspace']).then(); this._showAccessLog(loginToken.last_login_time, loginToken.last_login_ip, '/workspace'); } }); } else { this._logout(); Alert.error(this.translateService.instant('login.ui.failed'), true); this.loadingHide(); } }).catch((err) => { // 로딩 hide this.loadingHide(); if (err.details === 'INITIAL' || err.details === 'EXPIRED') { this.initialChangePasswordComponent.init(this.user.username, err.details); } else { this.loginFailMsg = err.details; } // this.commonExceptionHandler(err); }); } // function - login public initialComplete() { this.user.password = ''; this._pwElm.nativeElement.focus(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 로그아웃 * @private */ private _logout() { if (CommonUtil.isSamlSSO()) { location.href = '/saml/logout'; } else { this.cookieService.delete(CookieConstant.KEY.LOGIN_TOKEN, '/'); this.cookieService.delete(CookieConstant.KEY.LOGIN_TOKEN_TYPE, '/'); this.cookieService.delete(CookieConstant.KEY.LOGIN_USER_ID, '/'); this.cookieService.delete(CookieConstant.KEY.REFRESH_LOGIN_TOKEN, '/'); this.cookieService.delete(CookieConstant.KEY.CURRENT_WORKSPACE, '/'); this.cookieService.delete(CookieConstant.KEY.MY_WORKSPACE, '/'); this.cookieService.delete(CookieConstant.KEY.PERMISSION, '/'); } } // function - _logout private _showAccessLog(lastLoginTime: string, lastLoginIp: string, forwardUrl: string) { this.loadingHide(); const modal = new Modal(); modal.name = this.translateService.instant('msg.login.access.title'); modal.description = this.translateService.instant('msg.login.access.description') + moment(lastLoginTime).format('YYYY-MM-DD HH:mm:ss'); if (lastLoginIp !== undefined) { modal.description = modal.description + ' (' + lastLoginIp + ')'; } modal.data = forwardUrl; // confirm modal this.useCancelBtn = false; this._confirmModal.init(modal); } }
the_stack
import { gql } from '@apollo/client'; import * as Apollo from '@apollo/client'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; /** @model */ export type Comment = { __typename?: 'Comment'; /** @id */ id: Scalars['ID']; text?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; /** @manyToOne(field: 'comments', key: 'noteId') */ note?: Maybe<Note>; }; export type CommentFilter = { id?: Maybe<IdInput>; text?: Maybe<StringInput>; description?: Maybe<StringInput>; noteId?: Maybe<IdInput>; and?: Maybe<Array<CommentFilter>>; or?: Maybe<Array<CommentFilter>>; not?: Maybe<CommentFilter>; }; export type CommentResultList = { __typename?: 'CommentResultList'; items: Array<Maybe<Comment>>; offset?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; count?: Maybe<Scalars['Int']>; }; export type CommentSubscriptionFilter = { and?: Maybe<Array<CommentSubscriptionFilter>>; or?: Maybe<Array<CommentSubscriptionFilter>>; not?: Maybe<CommentSubscriptionFilter>; id?: Maybe<IdInput>; text?: Maybe<StringInput>; description?: Maybe<StringInput>; }; export type CreateCommentInput = { id?: Maybe<Scalars['ID']>; text?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; noteId?: Maybe<Scalars['ID']>; }; export type CreateNoteInput = { id?: Maybe<Scalars['ID']>; title: Scalars['String']; description?: Maybe<Scalars['String']>; }; export type IdInput = { ne?: Maybe<Scalars['ID']>; eq?: Maybe<Scalars['ID']>; le?: Maybe<Scalars['ID']>; lt?: Maybe<Scalars['ID']>; ge?: Maybe<Scalars['ID']>; gt?: Maybe<Scalars['ID']>; in?: Maybe<Array<Scalars['ID']>>; }; export type MutateCommentInput = { id: Scalars['ID']; text?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; noteId?: Maybe<Scalars['ID']>; }; export type MutateNoteInput = { id: Scalars['ID']; title?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; }; export type Mutation = { __typename?: 'Mutation'; createNote?: Maybe<Note>; updateNote?: Maybe<Note>; deleteNote?: Maybe<Note>; createComment?: Maybe<Comment>; updateComment?: Maybe<Comment>; deleteComment?: Maybe<Comment>; }; export type MutationCreateNoteArgs = { input: CreateNoteInput; }; export type MutationUpdateNoteArgs = { input: MutateNoteInput; }; export type MutationDeleteNoteArgs = { input: MutateNoteInput; }; export type MutationCreateCommentArgs = { input: CreateCommentInput; }; export type MutationUpdateCommentArgs = { input: MutateCommentInput; }; export type MutationDeleteCommentArgs = { input: MutateCommentInput; }; /** @model */ export type Note = { __typename?: 'Note'; /** @id */ id: Scalars['ID']; title: Scalars['String']; description?: Maybe<Scalars['String']>; /** * @oneToMany(field: 'note', key: 'noteId') * @oneToMany(field: 'note') */ comments: Array<Maybe<Comment>>; }; /** @model */ export type NoteCommentsArgs = { filter?: Maybe<CommentFilter>; }; export type NoteFilter = { id?: Maybe<IdInput>; title?: Maybe<StringInput>; description?: Maybe<StringInput>; and?: Maybe<Array<NoteFilter>>; or?: Maybe<Array<NoteFilter>>; not?: Maybe<NoteFilter>; }; export type NoteResultList = { __typename?: 'NoteResultList'; items: Array<Maybe<Note>>; offset?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; count?: Maybe<Scalars['Int']>; }; export type NoteSubscriptionFilter = { and?: Maybe<Array<NoteSubscriptionFilter>>; or?: Maybe<Array<NoteSubscriptionFilter>>; not?: Maybe<NoteSubscriptionFilter>; id?: Maybe<IdInput>; title?: Maybe<StringInput>; description?: Maybe<StringInput>; }; export type OrderByInput = { field: Scalars['String']; order?: Maybe<SortDirectionEnum>; }; export type PageRequest = { limit?: Maybe<Scalars['Int']>; offset?: Maybe<Scalars['Int']>; }; export type Query = { __typename?: 'Query'; getDraftNotes?: Maybe<Array<Maybe<Note>>>; getNote?: Maybe<Note>; findNotes: NoteResultList; getComment?: Maybe<Comment>; findComments: CommentResultList; }; export type QueryGetNoteArgs = { id: Scalars['ID']; }; export type QueryFindNotesArgs = { filter?: Maybe<NoteFilter>; page?: Maybe<PageRequest>; orderBy?: Maybe<OrderByInput>; }; export type QueryGetCommentArgs = { id: Scalars['ID']; }; export type QueryFindCommentsArgs = { filter?: Maybe<CommentFilter>; page?: Maybe<PageRequest>; orderBy?: Maybe<OrderByInput>; }; export enum SortDirectionEnum { Desc = 'DESC', Asc = 'ASC' } export type StringInput = { ne?: Maybe<Scalars['String']>; eq?: Maybe<Scalars['String']>; le?: Maybe<Scalars['String']>; lt?: Maybe<Scalars['String']>; ge?: Maybe<Scalars['String']>; gt?: Maybe<Scalars['String']>; in?: Maybe<Array<Scalars['String']>>; contains?: Maybe<Scalars['String']>; startsWith?: Maybe<Scalars['String']>; endsWith?: Maybe<Scalars['String']>; }; export type Subscription = { __typename?: 'Subscription'; newNote: Note; updatedNote: Note; deletedNote: Note; newComment: Comment; updatedComment: Comment; deletedComment: Comment; }; export type SubscriptionNewNoteArgs = { filter?: Maybe<NoteSubscriptionFilter>; }; export type SubscriptionUpdatedNoteArgs = { filter?: Maybe<NoteSubscriptionFilter>; }; export type SubscriptionDeletedNoteArgs = { filter?: Maybe<NoteSubscriptionFilter>; }; export type SubscriptionNewCommentArgs = { filter?: Maybe<CommentSubscriptionFilter>; }; export type SubscriptionUpdatedCommentArgs = { filter?: Maybe<CommentSubscriptionFilter>; }; export type SubscriptionDeletedCommentArgs = { filter?: Maybe<CommentSubscriptionFilter>; }; export type GetDraftNotesQueryVariables = Exact<{ [key: string]: never; }>; export type GetDraftNotesQuery = ( { __typename?: 'Query' } & { getDraftNotes?: Maybe<Array<Maybe<( { __typename?: 'Note' } & NoteExpandedFieldsFragment )>>> } ); export type NoteFieldsFragment = ( { __typename?: 'Note' } & Pick<Note, 'id' | 'title' | 'description'> ); export type NoteExpandedFieldsFragment = ( { __typename?: 'Note' } & Pick<Note, 'id' | 'title' | 'description'> & { comments: Array<Maybe<( { __typename?: 'Comment' } & Pick<Comment, 'id' | 'text' | 'description'> )>> } ); export type CommentFieldsFragment = ( { __typename?: 'Comment' } & Pick<Comment, 'id' | 'text' | 'description'> ); export type CommentExpandedFieldsFragment = ( { __typename?: 'Comment' } & Pick<Comment, 'id' | 'text' | 'description'> & { note?: Maybe<( { __typename?: 'Note' } & Pick<Note, 'id' | 'title' | 'description'> )> } ); export type FindNotesQueryVariables = Exact<{ filter?: Maybe<NoteFilter>; page?: Maybe<PageRequest>; orderBy?: Maybe<OrderByInput>; }>; export type FindNotesQuery = ( { __typename?: 'Query' } & { findNotes: ( { __typename?: 'NoteResultList' } & Pick<NoteResultList, 'offset' | 'limit' | 'count'> & { items: Array<Maybe<( { __typename?: 'Note' } & NoteExpandedFieldsFragment )>> } ) } ); export type GetNoteQueryVariables = Exact<{ id: Scalars['ID']; }>; export type GetNoteQuery = ( { __typename?: 'Query' } & { getNote?: Maybe<( { __typename?: 'Note' } & NoteExpandedFieldsFragment )> } ); export type FindCommentsQueryVariables = Exact<{ filter?: Maybe<CommentFilter>; page?: Maybe<PageRequest>; orderBy?: Maybe<OrderByInput>; }>; export type FindCommentsQuery = ( { __typename?: 'Query' } & { findComments: ( { __typename?: 'CommentResultList' } & Pick<CommentResultList, 'offset' | 'limit' | 'count'> & { items: Array<Maybe<( { __typename?: 'Comment' } & CommentExpandedFieldsFragment )>> } ) } ); export type GetCommentQueryVariables = Exact<{ id: Scalars['ID']; }>; export type GetCommentQuery = ( { __typename?: 'Query' } & { getComment?: Maybe<( { __typename?: 'Comment' } & CommentExpandedFieldsFragment )> } ); export type CreateNoteMutationVariables = Exact<{ input: CreateNoteInput; }>; export type CreateNoteMutation = ( { __typename?: 'Mutation' } & { createNote?: Maybe<( { __typename?: 'Note' } & NoteFieldsFragment )> } ); export type UpdateNoteMutationVariables = Exact<{ input: MutateNoteInput; }>; export type UpdateNoteMutation = ( { __typename?: 'Mutation' } & { updateNote?: Maybe<( { __typename?: 'Note' } & NoteFieldsFragment )> } ); export type DeleteNoteMutationVariables = Exact<{ input: MutateNoteInput; }>; export type DeleteNoteMutation = ( { __typename?: 'Mutation' } & { deleteNote?: Maybe<( { __typename?: 'Note' } & NoteFieldsFragment )> } ); export type CreateCommentMutationVariables = Exact<{ input: CreateCommentInput; }>; export type CreateCommentMutation = ( { __typename?: 'Mutation' } & { createComment?: Maybe<( { __typename?: 'Comment' } & CommentFieldsFragment )> } ); export type UpdateCommentMutationVariables = Exact<{ input: MutateCommentInput; }>; export type UpdateCommentMutation = ( { __typename?: 'Mutation' } & { updateComment?: Maybe<( { __typename?: 'Comment' } & CommentFieldsFragment )> } ); export type DeleteCommentMutationVariables = Exact<{ input: MutateCommentInput; }>; export type DeleteCommentMutation = ( { __typename?: 'Mutation' } & { deleteComment?: Maybe<( { __typename?: 'Comment' } & CommentFieldsFragment )> } ); export type NewNoteSubscriptionVariables = Exact<{ filter?: Maybe<NoteSubscriptionFilter>; }>; export type NewNoteSubscription = ( { __typename?: 'Subscription' } & { newNote: ( { __typename?: 'Note' } & NoteFieldsFragment ) } ); export type UpdatedNoteSubscriptionVariables = Exact<{ filter?: Maybe<NoteSubscriptionFilter>; }>; export type UpdatedNoteSubscription = ( { __typename?: 'Subscription' } & { updatedNote: ( { __typename?: 'Note' } & NoteFieldsFragment ) } ); export type DeletedNoteSubscriptionVariables = Exact<{ filter?: Maybe<NoteSubscriptionFilter>; }>; export type DeletedNoteSubscription = ( { __typename?: 'Subscription' } & { deletedNote: ( { __typename?: 'Note' } & NoteFieldsFragment ) } ); export type NewCommentSubscriptionVariables = Exact<{ filter?: Maybe<CommentSubscriptionFilter>; }>; export type NewCommentSubscription = ( { __typename?: 'Subscription' } & { newComment: ( { __typename?: 'Comment' } & CommentFieldsFragment ) } ); export type UpdatedCommentSubscriptionVariables = Exact<{ filter?: Maybe<CommentSubscriptionFilter>; }>; export type UpdatedCommentSubscription = ( { __typename?: 'Subscription' } & { updatedComment: ( { __typename?: 'Comment' } & CommentFieldsFragment ) } ); export type DeletedCommentSubscriptionVariables = Exact<{ filter?: Maybe<CommentSubscriptionFilter>; }>; export type DeletedCommentSubscription = ( { __typename?: 'Subscription' } & { deletedComment: ( { __typename?: 'Comment' } & CommentFieldsFragment ) } ); export const NoteFieldsFragmentDoc = gql` fragment NoteFields on Note { id title description } `; export const NoteExpandedFieldsFragmentDoc = gql` fragment NoteExpandedFields on Note { id title description comments { id text description } } `; export const CommentFieldsFragmentDoc = gql` fragment CommentFields on Comment { id text description } `; export const CommentExpandedFieldsFragmentDoc = gql` fragment CommentExpandedFields on Comment { id text description note { id title description } } `; export const GetDraftNotesDocument = gql` query getDraftNotes { getDraftNotes { ...NoteExpandedFields } } ${NoteExpandedFieldsFragmentDoc}`; /** * __useGetDraftNotesQuery__ * * To run a query within a React component, call `useGetDraftNotesQuery` and pass it any options that fit your needs. * When your component renders, `useGetDraftNotesQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetDraftNotesQuery({ * variables: { * }, * }); */ export function useGetDraftNotesQuery(baseOptions?: Apollo.QueryHookOptions<GetDraftNotesQuery, GetDraftNotesQueryVariables>) { return Apollo.useQuery<GetDraftNotesQuery, GetDraftNotesQueryVariables>(GetDraftNotesDocument, baseOptions); } export function useGetDraftNotesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetDraftNotesQuery, GetDraftNotesQueryVariables>) { return Apollo.useLazyQuery<GetDraftNotesQuery, GetDraftNotesQueryVariables>(GetDraftNotesDocument, baseOptions); } export type GetDraftNotesQueryHookResult = ReturnType<typeof useGetDraftNotesQuery>; export type GetDraftNotesLazyQueryHookResult = ReturnType<typeof useGetDraftNotesLazyQuery>; export type GetDraftNotesQueryResult = Apollo.QueryResult<GetDraftNotesQuery, GetDraftNotesQueryVariables>; export const FindNotesDocument = gql` query findNotes($filter: NoteFilter, $page: PageRequest, $orderBy: OrderByInput) { findNotes(filter: $filter, page: $page, orderBy: $orderBy) { items { ...NoteExpandedFields } offset limit count } } ${NoteExpandedFieldsFragmentDoc}`; /** * __useFindNotesQuery__ * * To run a query within a React component, call `useFindNotesQuery` and pass it any options that fit your needs. * When your component renders, `useFindNotesQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useFindNotesQuery({ * variables: { * filter: // value for 'filter' * page: // value for 'page' * orderBy: // value for 'orderBy' * }, * }); */ export function useFindNotesQuery(baseOptions?: Apollo.QueryHookOptions<FindNotesQuery, FindNotesQueryVariables>) { return Apollo.useQuery<FindNotesQuery, FindNotesQueryVariables>(FindNotesDocument, baseOptions); } export function useFindNotesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<FindNotesQuery, FindNotesQueryVariables>) { return Apollo.useLazyQuery<FindNotesQuery, FindNotesQueryVariables>(FindNotesDocument, baseOptions); } export type FindNotesQueryHookResult = ReturnType<typeof useFindNotesQuery>; export type FindNotesLazyQueryHookResult = ReturnType<typeof useFindNotesLazyQuery>; export type FindNotesQueryResult = Apollo.QueryResult<FindNotesQuery, FindNotesQueryVariables>; export const GetNoteDocument = gql` query getNote($id: ID!) { getNote(id: $id) { ...NoteExpandedFields } } ${NoteExpandedFieldsFragmentDoc}`; /** * __useGetNoteQuery__ * * To run a query within a React component, call `useGetNoteQuery` and pass it any options that fit your needs. * When your component renders, `useGetNoteQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetNoteQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useGetNoteQuery(baseOptions?: Apollo.QueryHookOptions<GetNoteQuery, GetNoteQueryVariables>) { return Apollo.useQuery<GetNoteQuery, GetNoteQueryVariables>(GetNoteDocument, baseOptions); } export function useGetNoteLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetNoteQuery, GetNoteQueryVariables>) { return Apollo.useLazyQuery<GetNoteQuery, GetNoteQueryVariables>(GetNoteDocument, baseOptions); } export type GetNoteQueryHookResult = ReturnType<typeof useGetNoteQuery>; export type GetNoteLazyQueryHookResult = ReturnType<typeof useGetNoteLazyQuery>; export type GetNoteQueryResult = Apollo.QueryResult<GetNoteQuery, GetNoteQueryVariables>; export const FindCommentsDocument = gql` query findComments($filter: CommentFilter, $page: PageRequest, $orderBy: OrderByInput) { findComments(filter: $filter, page: $page, orderBy: $orderBy) { items { ...CommentExpandedFields } offset limit count } } ${CommentExpandedFieldsFragmentDoc}`; /** * __useFindCommentsQuery__ * * To run a query within a React component, call `useFindCommentsQuery` and pass it any options that fit your needs. * When your component renders, `useFindCommentsQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useFindCommentsQuery({ * variables: { * filter: // value for 'filter' * page: // value for 'page' * orderBy: // value for 'orderBy' * }, * }); */ export function useFindCommentsQuery(baseOptions?: Apollo.QueryHookOptions<FindCommentsQuery, FindCommentsQueryVariables>) { return Apollo.useQuery<FindCommentsQuery, FindCommentsQueryVariables>(FindCommentsDocument, baseOptions); } export function useFindCommentsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<FindCommentsQuery, FindCommentsQueryVariables>) { return Apollo.useLazyQuery<FindCommentsQuery, FindCommentsQueryVariables>(FindCommentsDocument, baseOptions); } export type FindCommentsQueryHookResult = ReturnType<typeof useFindCommentsQuery>; export type FindCommentsLazyQueryHookResult = ReturnType<typeof useFindCommentsLazyQuery>; export type FindCommentsQueryResult = Apollo.QueryResult<FindCommentsQuery, FindCommentsQueryVariables>; export const GetCommentDocument = gql` query getComment($id: ID!) { getComment(id: $id) { ...CommentExpandedFields } } ${CommentExpandedFieldsFragmentDoc}`; /** * __useGetCommentQuery__ * * To run a query within a React component, call `useGetCommentQuery` and pass it any options that fit your needs. * When your component renders, `useGetCommentQuery` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useGetCommentQuery({ * variables: { * id: // value for 'id' * }, * }); */ export function useGetCommentQuery(baseOptions?: Apollo.QueryHookOptions<GetCommentQuery, GetCommentQueryVariables>) { return Apollo.useQuery<GetCommentQuery, GetCommentQueryVariables>(GetCommentDocument, baseOptions); } export function useGetCommentLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetCommentQuery, GetCommentQueryVariables>) { return Apollo.useLazyQuery<GetCommentQuery, GetCommentQueryVariables>(GetCommentDocument, baseOptions); } export type GetCommentQueryHookResult = ReturnType<typeof useGetCommentQuery>; export type GetCommentLazyQueryHookResult = ReturnType<typeof useGetCommentLazyQuery>; export type GetCommentQueryResult = Apollo.QueryResult<GetCommentQuery, GetCommentQueryVariables>; export const CreateNoteDocument = gql` mutation createNote($input: CreateNoteInput!) { createNote(input: $input) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; export type CreateNoteMutationFn = Apollo.MutationFunction<CreateNoteMutation, CreateNoteMutationVariables>; /** * __useCreateNoteMutation__ * * To run a mutation, you first call `useCreateNoteMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateNoteMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createNoteMutation, { data, loading, error }] = useCreateNoteMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useCreateNoteMutation(baseOptions?: Apollo.MutationHookOptions<CreateNoteMutation, CreateNoteMutationVariables>) { return Apollo.useMutation<CreateNoteMutation, CreateNoteMutationVariables>(CreateNoteDocument, baseOptions); } export type CreateNoteMutationHookResult = ReturnType<typeof useCreateNoteMutation>; export type CreateNoteMutationResult = Apollo.MutationResult<CreateNoteMutation>; export type CreateNoteMutationOptions = Apollo.BaseMutationOptions<CreateNoteMutation, CreateNoteMutationVariables>; export const UpdateNoteDocument = gql` mutation updateNote($input: MutateNoteInput!) { updateNote(input: $input) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; export type UpdateNoteMutationFn = Apollo.MutationFunction<UpdateNoteMutation, UpdateNoteMutationVariables>; /** * __useUpdateNoteMutation__ * * To run a mutation, you first call `useUpdateNoteMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdateNoteMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updateNoteMutation, { data, loading, error }] = useUpdateNoteMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useUpdateNoteMutation(baseOptions?: Apollo.MutationHookOptions<UpdateNoteMutation, UpdateNoteMutationVariables>) { return Apollo.useMutation<UpdateNoteMutation, UpdateNoteMutationVariables>(UpdateNoteDocument, baseOptions); } export type UpdateNoteMutationHookResult = ReturnType<typeof useUpdateNoteMutation>; export type UpdateNoteMutationResult = Apollo.MutationResult<UpdateNoteMutation>; export type UpdateNoteMutationOptions = Apollo.BaseMutationOptions<UpdateNoteMutation, UpdateNoteMutationVariables>; export const DeleteNoteDocument = gql` mutation deleteNote($input: MutateNoteInput!) { deleteNote(input: $input) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; export type DeleteNoteMutationFn = Apollo.MutationFunction<DeleteNoteMutation, DeleteNoteMutationVariables>; /** * __useDeleteNoteMutation__ * * To run a mutation, you first call `useDeleteNoteMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteNoteMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteNoteMutation, { data, loading, error }] = useDeleteNoteMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useDeleteNoteMutation(baseOptions?: Apollo.MutationHookOptions<DeleteNoteMutation, DeleteNoteMutationVariables>) { return Apollo.useMutation<DeleteNoteMutation, DeleteNoteMutationVariables>(DeleteNoteDocument, baseOptions); } export type DeleteNoteMutationHookResult = ReturnType<typeof useDeleteNoteMutation>; export type DeleteNoteMutationResult = Apollo.MutationResult<DeleteNoteMutation>; export type DeleteNoteMutationOptions = Apollo.BaseMutationOptions<DeleteNoteMutation, DeleteNoteMutationVariables>; export const CreateCommentDocument = gql` mutation createComment($input: CreateCommentInput!) { createComment(input: $input) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; export type CreateCommentMutationFn = Apollo.MutationFunction<CreateCommentMutation, CreateCommentMutationVariables>; /** * __useCreateCommentMutation__ * * To run a mutation, you first call `useCreateCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useCreateCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [createCommentMutation, { data, loading, error }] = useCreateCommentMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useCreateCommentMutation(baseOptions?: Apollo.MutationHookOptions<CreateCommentMutation, CreateCommentMutationVariables>) { return Apollo.useMutation<CreateCommentMutation, CreateCommentMutationVariables>(CreateCommentDocument, baseOptions); } export type CreateCommentMutationHookResult = ReturnType<typeof useCreateCommentMutation>; export type CreateCommentMutationResult = Apollo.MutationResult<CreateCommentMutation>; export type CreateCommentMutationOptions = Apollo.BaseMutationOptions<CreateCommentMutation, CreateCommentMutationVariables>; export const UpdateCommentDocument = gql` mutation updateComment($input: MutateCommentInput!) { updateComment(input: $input) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; export type UpdateCommentMutationFn = Apollo.MutationFunction<UpdateCommentMutation, UpdateCommentMutationVariables>; /** * __useUpdateCommentMutation__ * * To run a mutation, you first call `useUpdateCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useUpdateCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [updateCommentMutation, { data, loading, error }] = useUpdateCommentMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useUpdateCommentMutation(baseOptions?: Apollo.MutationHookOptions<UpdateCommentMutation, UpdateCommentMutationVariables>) { return Apollo.useMutation<UpdateCommentMutation, UpdateCommentMutationVariables>(UpdateCommentDocument, baseOptions); } export type UpdateCommentMutationHookResult = ReturnType<typeof useUpdateCommentMutation>; export type UpdateCommentMutationResult = Apollo.MutationResult<UpdateCommentMutation>; export type UpdateCommentMutationOptions = Apollo.BaseMutationOptions<UpdateCommentMutation, UpdateCommentMutationVariables>; export const DeleteCommentDocument = gql` mutation deleteComment($input: MutateCommentInput!) { deleteComment(input: $input) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; export type DeleteCommentMutationFn = Apollo.MutationFunction<DeleteCommentMutation, DeleteCommentMutationVariables>; /** * __useDeleteCommentMutation__ * * To run a mutation, you first call `useDeleteCommentMutation` within a React component and pass it any options that fit your needs. * When your component renders, `useDeleteCommentMutation` returns a tuple that includes: * - A mutate function that you can call at any time to execute the mutation * - An object with fields that represent the current status of the mutation's execution * * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2; * * @example * const [deleteCommentMutation, { data, loading, error }] = useDeleteCommentMutation({ * variables: { * input: // value for 'input' * }, * }); */ export function useDeleteCommentMutation(baseOptions?: Apollo.MutationHookOptions<DeleteCommentMutation, DeleteCommentMutationVariables>) { return Apollo.useMutation<DeleteCommentMutation, DeleteCommentMutationVariables>(DeleteCommentDocument, baseOptions); } export type DeleteCommentMutationHookResult = ReturnType<typeof useDeleteCommentMutation>; export type DeleteCommentMutationResult = Apollo.MutationResult<DeleteCommentMutation>; export type DeleteCommentMutationOptions = Apollo.BaseMutationOptions<DeleteCommentMutation, DeleteCommentMutationVariables>; export const NewNoteDocument = gql` subscription newNote($filter: NoteSubscriptionFilter) { newNote(filter: $filter) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; /** * __useNewNoteSubscription__ * * To run a query within a React component, call `useNewNoteSubscription` and pass it any options that fit your needs. * When your component renders, `useNewNoteSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useNewNoteSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useNewNoteSubscription(baseOptions?: Apollo.SubscriptionHookOptions<NewNoteSubscription, NewNoteSubscriptionVariables>) { return Apollo.useSubscription<NewNoteSubscription, NewNoteSubscriptionVariables>(NewNoteDocument, baseOptions); } export type NewNoteSubscriptionHookResult = ReturnType<typeof useNewNoteSubscription>; export type NewNoteSubscriptionResult = Apollo.SubscriptionResult<NewNoteSubscription>; export const UpdatedNoteDocument = gql` subscription updatedNote($filter: NoteSubscriptionFilter) { updatedNote(filter: $filter) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; /** * __useUpdatedNoteSubscription__ * * To run a query within a React component, call `useUpdatedNoteSubscription` and pass it any options that fit your needs. * When your component renders, `useUpdatedNoteSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useUpdatedNoteSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useUpdatedNoteSubscription(baseOptions?: Apollo.SubscriptionHookOptions<UpdatedNoteSubscription, UpdatedNoteSubscriptionVariables>) { return Apollo.useSubscription<UpdatedNoteSubscription, UpdatedNoteSubscriptionVariables>(UpdatedNoteDocument, baseOptions); } export type UpdatedNoteSubscriptionHookResult = ReturnType<typeof useUpdatedNoteSubscription>; export type UpdatedNoteSubscriptionResult = Apollo.SubscriptionResult<UpdatedNoteSubscription>; export const DeletedNoteDocument = gql` subscription deletedNote($filter: NoteSubscriptionFilter) { deletedNote(filter: $filter) { ...NoteFields } } ${NoteFieldsFragmentDoc}`; /** * __useDeletedNoteSubscription__ * * To run a query within a React component, call `useDeletedNoteSubscription` and pass it any options that fit your needs. * When your component renders, `useDeletedNoteSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDeletedNoteSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useDeletedNoteSubscription(baseOptions?: Apollo.SubscriptionHookOptions<DeletedNoteSubscription, DeletedNoteSubscriptionVariables>) { return Apollo.useSubscription<DeletedNoteSubscription, DeletedNoteSubscriptionVariables>(DeletedNoteDocument, baseOptions); } export type DeletedNoteSubscriptionHookResult = ReturnType<typeof useDeletedNoteSubscription>; export type DeletedNoteSubscriptionResult = Apollo.SubscriptionResult<DeletedNoteSubscription>; export const NewCommentDocument = gql` subscription newComment($filter: CommentSubscriptionFilter) { newComment(filter: $filter) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; /** * __useNewCommentSubscription__ * * To run a query within a React component, call `useNewCommentSubscription` and pass it any options that fit your needs. * When your component renders, `useNewCommentSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useNewCommentSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useNewCommentSubscription(baseOptions?: Apollo.SubscriptionHookOptions<NewCommentSubscription, NewCommentSubscriptionVariables>) { return Apollo.useSubscription<NewCommentSubscription, NewCommentSubscriptionVariables>(NewCommentDocument, baseOptions); } export type NewCommentSubscriptionHookResult = ReturnType<typeof useNewCommentSubscription>; export type NewCommentSubscriptionResult = Apollo.SubscriptionResult<NewCommentSubscription>; export const UpdatedCommentDocument = gql` subscription updatedComment($filter: CommentSubscriptionFilter) { updatedComment(filter: $filter) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; /** * __useUpdatedCommentSubscription__ * * To run a query within a React component, call `useUpdatedCommentSubscription` and pass it any options that fit your needs. * When your component renders, `useUpdatedCommentSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useUpdatedCommentSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useUpdatedCommentSubscription(baseOptions?: Apollo.SubscriptionHookOptions<UpdatedCommentSubscription, UpdatedCommentSubscriptionVariables>) { return Apollo.useSubscription<UpdatedCommentSubscription, UpdatedCommentSubscriptionVariables>(UpdatedCommentDocument, baseOptions); } export type UpdatedCommentSubscriptionHookResult = ReturnType<typeof useUpdatedCommentSubscription>; export type UpdatedCommentSubscriptionResult = Apollo.SubscriptionResult<UpdatedCommentSubscription>; export const DeletedCommentDocument = gql` subscription deletedComment($filter: CommentSubscriptionFilter) { deletedComment(filter: $filter) { ...CommentFields } } ${CommentFieldsFragmentDoc}`; /** * __useDeletedCommentSubscription__ * * To run a query within a React component, call `useDeletedCommentSubscription` and pass it any options that fit your needs. * When your component renders, `useDeletedCommentSubscription` returns an object from Apollo Client that contains loading, error, and data properties * you can use to render your UI. * * @param baseOptions options that will be passed into the subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; * * @example * const { data, loading, error } = useDeletedCommentSubscription({ * variables: { * filter: // value for 'filter' * }, * }); */ export function useDeletedCommentSubscription(baseOptions?: Apollo.SubscriptionHookOptions<DeletedCommentSubscription, DeletedCommentSubscriptionVariables>) { return Apollo.useSubscription<DeletedCommentSubscription, DeletedCommentSubscriptionVariables>(DeletedCommentDocument, baseOptions); } export type DeletedCommentSubscriptionHookResult = ReturnType<typeof useDeletedCommentSubscription>; export type DeletedCommentSubscriptionResult = Apollo.SubscriptionResult<DeletedCommentSubscription>;
the_stack
import _ from 'lodash'; import { omitUndefinedValues, repository } from 'src/repository/repository'; import { getItemsKnex, generateColumnNames } from 'src/knex/queries/items'; import { Database } from 'src/dbconfig'; import { getDetailsKnex } from 'src/knex/queries/details'; import { Seen } from 'src/entity/seen'; import { UserRating } from 'src/entity/userRating'; import { NotificationsHistory } from 'src/entity/notificationsHistory'; import { TvEpisode, tvEpisodeColumns } from 'src/entity/tvepisode'; import { tvSeasonRepository } from 'src/repository/season'; import { tvEpisodeRepository } from 'src/repository/episode'; import { ExternalIds, MediaItemBase, MediaItemBaseWithSeasons, mediaItemColumns, MediaItemForProvider, MediaItemItemsResponse, mediaItemSlug, MediaType, } from 'src/entity/mediaItem'; import { imageRepository } from 'src/repository/image'; import { getImageId, Image } from 'src/entity/image'; import { subDays } from 'date-fns'; import { randomSlugId } from 'src/slug'; import { TvSeason } from 'src/entity/tvseason'; import { ListItem } from 'src/entity/list'; export type MediaItemOrderBy = | 'title' | 'lastSeen' | 'unseenEpisodes' | 'releaseDate' | 'nextAiring' | 'lastAiring' | 'status' | 'progress' | 'mediaType'; export type SortOrder = 'asc' | 'desc'; export type LastSeenAt = 'now' | 'release_date' | 'unknown' | 'custom_date'; export type Pagination<T> = { data: T[]; page: number; totalPages: number; from: number; to: number; total: number; }; export type GetItemsArgs = { userId: number; mediaType?: MediaType; orderBy?: MediaItemOrderBy; sortOrder?: SortOrder; /** * @description Return only items with title including this phrase */ filter?: string; /** * @description Return only items on watchlist */ onlyOnWatchlist?: boolean; /** * @description Return only seen items */ onlySeenItems?: boolean; /** * @description */ onlyWithNextEpisodesToWatch?: boolean; /** * @description Return only items with upcoming episode with release date, or unreleased other media with release date */ onlyWithNextAiring?: boolean; /** * @description Return only items with user rating */ onlyWithUserRating?: boolean; /** * @description Return only items without user rating */ onlyWithoutUserRating?: boolean; onlyWithProgress?: boolean; page?: number; mediaItemIds?: number[]; }; class MediaItemRepository extends repository<MediaItemBase>({ tableName: 'mediaItem', columnNames: mediaItemColumns, primaryColumnName: 'id', booleanColumnNames: ['needsDetails'], }) { public items( args: GetItemsArgs & { page: number } ): Promise<Pagination<MediaItemItemsResponse>>; public items( args: Omit<GetItemsArgs, 'page'> ): Promise<MediaItemItemsResponse[]>; public items(args: never): Promise<unknown> { return getItemsKnex(args); } public async details(params: { mediaItemId: number; userId: number }) { return getDetailsKnex(params); } public deserialize(value: Partial<MediaItemBase>): MediaItemBase { return super.deserialize({ ...value, genres: (value.genres as unknown as string)?.split(',') || null, narrators: (value.narrators as unknown as string)?.split(',') || null, authors: (value.authors as unknown as string)?.split(',') || null, platform: value.platform ? JSON.parse(value.platform as unknown as string) : null, }); } public serialize(value: Partial<MediaItemBase>) { return super.serialize({ ...value, genres: value.genres?.join(','), authors: value.authors?.join(','), narrators: value.narrators?.join(','), platform: value.platform ? JSON.stringify(value.platform) : null, } as unknown) as Record<string, unknown>; } public async delete(where?: { id: number }) { const mediaItemId = where.id; return await Database.knex.transaction(async (trx) => { await trx<Image>('image').delete().where('mediaItemId', mediaItemId); await trx<NotificationsHistory>('notificationsHistory') .delete() .where('mediaItemId', mediaItemId); await trx<TvEpisode>('episode').delete().where('tvShowId', mediaItemId); await trx<TvSeason>('season').delete().where('tvShowId', mediaItemId); return await trx<MediaItemBase>(this.tableName) .delete() .where('id', mediaItemId); }); } public async update( mediaItem: MediaItemBaseWithSeasons ): Promise<MediaItemBaseWithSeasons> { if (!mediaItem.id) { throw new Error('mediaItem.id filed is required'); } const slug = mediaItemSlug(mediaItem); return await Database.knex.transaction(async (trx) => { const result = { ..._.cloneDeep(mediaItem), lastTimeUpdated: mediaItem.lastTimeUpdated ? mediaItem.lastTimeUpdated : new Date().getTime(), }; await trx(this.tableName) .update({ ...this.serialize(this.stripValue(mediaItem)), slug: Database.knex.raw( `(CASE WHEN ( ${Database.knex<MediaItemBase>('mediaItem') .count() .where('slug', slug) .whereNot('id', mediaItem.id) .toQuery()}) = 0 THEN '${slug}' ELSE '${slug}-${randomSlugId()}' END)` ), }) .where({ id: mediaItem.id, }); if (!mediaItem.poster) { await trx(imageRepository.tableName).delete().where({ mediaItemId: mediaItem.id, seasonId: null, type: 'poster', }); } else { const res = await trx(imageRepository.tableName).where({ mediaItemId: mediaItem.id, seasonId: null, type: 'poster', }); if (res.length === 0) { const posterId = getImageId(); await trx(imageRepository.tableName).insert({ id: getImageId(), mediaItemId: mediaItem.id, seasonId: null, type: 'poster', }); result.poster = `/img/${posterId}`; } } if (!mediaItem.backdrop) { await trx(imageRepository.tableName).delete().where({ mediaItemId: mediaItem.id, seasonId: null, type: 'backdrop', }); } else { const res = await trx(imageRepository.tableName).where({ mediaItemId: mediaItem.id, seasonId: null, type: 'backdrop', }); if (res.length === 0) { await trx(imageRepository.tableName).insert({ id: getImageId(), mediaItemId: mediaItem.id, seasonId: null, type: 'backdrop', }); } } if (result.seasons) { for (const season of result.seasons) { let updated = false; season.numberOfEpisodes = season.numberOfEpisodes || season.episodes?.length || 0; season.tvShowId = mediaItem.id; const newSeason = omitUndefinedValues( tvSeasonRepository.stripValue(tvSeasonRepository.serialize(season)) ); if (season.id) { const res = await trx('season') .update(newSeason) .where({ id: season.id }); updated = res === 1; } if (!updated) { season.id = ( await trx('season').insert(newSeason).returning('id') ).at(0).id; } if (!season.poster) { await trx(imageRepository.tableName).delete().where({ mediaItemId: mediaItem.id, seasonId: season.id, type: 'poster', }); } else { const res = await trx(imageRepository.tableName).where({ mediaItemId: mediaItem.id, seasonId: season.id, type: 'poster', }); if (res.length === 0) { await trx(imageRepository.tableName).insert({ id: getImageId(), mediaItemId: mediaItem.id, seasonId: season.id, type: 'poster', }); } } if (season.episodes) { for (const episode of season.episodes) { let updated = false; episode.seasonAndEpisodeNumber = episode.seasonNumber * 1000 + episode.episodeNumber; episode.seasonId = season.id; episode.tvShowId = mediaItem.id; const newEpisode = omitUndefinedValues( tvEpisodeRepository.stripValue( tvEpisodeRepository.serialize(episode) ) ); if (episode.id) { const res = await trx<TvEpisode>('episode') .update(newEpisode) .where({ id: episode.id }); updated = res === 1; } if (!updated) { episode.id = ( await trx('episode').insert(newEpisode).returning('id') ).at(0).id; } } } } } return result; }); } public async create(mediaItem: MediaItemBaseWithSeasons) { const slug = mediaItemSlug(mediaItem); return await Database.knex.transaction(async (trx) => { const result = { ..._.cloneDeep(mediaItem), lastTimeUpdated: mediaItem.lastTimeUpdated ? mediaItem.lastTimeUpdated : new Date().getTime(), }; const res = await trx(this.tableName) .insert({ ...this.serialize(omitUndefinedValues(this.stripValue(mediaItem))), slug: Database.knex.raw( `(CASE WHEN ( ${Database.knex<MediaItemBase>('mediaItem') .count() .where('slug', slug) .toQuery()}) = 0 THEN '${slug}' ELSE '${slug}-${randomSlugId()}' END)` ), }) .returning(this.primaryColumnName); result.id = res.at(0)[this.primaryColumnName]; if (result.poster) { const imageId = getImageId(); await trx(imageRepository.tableName).insert({ id: imageId, mediaItemId: result.id, type: 'poster', }); result.poster = `/img/${imageId}`; } if (result.backdrop) { const imageId = getImageId(); await trx(imageRepository.tableName).insert({ id: imageId, mediaItemId: result.id, type: 'backdrop', }); result.backdrop = `/img/${imageId}`; } result.seasons = result.seasons?.map((season) => ({ ...season, numberOfEpisodes: season.numberOfEpisodes || season.episodes?.length || 0, tvShowId: result.id, })); if (result.seasons?.length > 0) { const seasonsId = await Database.knex .batchInsert( 'season', result.seasons.map((season) => _.omit(season, 'episodes')), 30 ) .transacting(trx) .returning('id'); result.seasons = _.merge(result.seasons, seasonsId); const seasonsWithPosters = result.seasons.filter( (season) => season.poster ); if (seasonsWithPosters.length > 0) { await Database.knex .batchInsert( imageRepository.tableName, seasonsWithPosters.map((season) => ({ id: getImageId(), mediaItemId: result.id, seasonId: season.id, type: 'poster', })), 30 ) .transacting(trx); } for (const season of result.seasons) { if (season.episodes?.length > 0) { season.episodes = season.episodes?.map((episode) => ({ ...episode, tvShowId: result.id, seasonId: season.id, seasonAndEpisodeNumber: episode.seasonNumber * 1000 + episode.episodeNumber, })); const episodesId = await Database.knex .batchInsert('episode', season.episodes, 30) .transacting(trx) .returning('id'); season.episodes = _.merge(season.episodes, episodesId); } } } return result; }); } public async createMany(mediaItem: MediaItemBaseWithSeasons[]) { return await Promise.all( mediaItem.map((mediaItem) => this.create(mediaItem)) ); } public async seasonsWithEpisodes(mediaItem: MediaItemBase) { const seasons = await tvSeasonRepository.find({ tvShowId: Number(mediaItem.id), }); const episodes = await tvEpisodeRepository.find({ tvShowId: Number(mediaItem.id), }); const groupedEpisodes = _.groupBy(episodes, (episode) => episode.seasonId); seasons.forEach((season) => (season.episodes = groupedEpisodes[season.id])); return seasons; } public async findByExternalIds(params: { tmdbId?: number[]; imdbId?: string[]; tvmazeId?: number[]; igdbId?: number[]; openlibraryId?: number[]; audibleId?: string[]; goodreadsId?: number[]; traktId?: number[]; tvdbId?: number[]; mediaType: MediaType; }) { return ( await Database.knex<MediaItemBase>(this.tableName) .where({ mediaType: params.mediaType }) .andWhere((qb) => { if (params.tmdbId) { qb.orWhereIn('tmdbId', params.tmdbId); } if (params.imdbId) { qb.orWhereIn('imdbId', params.imdbId); } if (params.tvmazeId) { qb.orWhereIn('tvmazeId', params.tvmazeId); } if (params.igdbId) { qb.orWhereIn('igdbId', params.igdbId); } if (params.openlibraryId) { qb.orWhereIn('openlibraryId', params.openlibraryId); } if (params.audibleId) { qb.orWhereIn('audibleId', params.audibleId); } if (params.goodreadsId) { qb.orWhereIn('goodreadsId', params.goodreadsId); } if (params.traktId) { qb.orWhereIn('traktId', params.traktId); } if (params.tvdbId) { qb.orWhereIn('tvdbId', params.tvdbId); } }) ).map((item) => this.deserialize(item)); } public async findByExternalId(params: ExternalIds, mediaType: MediaType) { const res = await Database.knex<MediaItemBase>(this.tableName) .where({ mediaType: mediaType }) .andWhere((qb) => { if (params.tmdbId) { qb.orWhere('tmdbId', params.tmdbId); } if (params.imdbId) { qb.orWhere('imdbId', params.imdbId); } if (params.tvmazeId) { qb.orWhere('tvmazeId', params.tvmazeId); } if (params.igdbId) { qb.orWhere('igdbId', params.igdbId); } if (params.openlibraryId) { qb.orWhere('openlibraryId', params.openlibraryId); } if (params.audibleId) { qb.orWhere('audibleId', params.audibleId); } if (params.goodreadsId) { qb.orWhere('goodreadsId', params.goodreadsId); } if (params.traktId) { qb.orWhere('traktId', params.traktId); } if (params.tvdbId) { qb.orWhere('tvdbId', params.tvdbId); } }) .first(); if (res) { return this.deserialize(res); } } public async findByTitle(params: { mediaType: MediaType; title: string; releaseYear?: number; }): Promise<MediaItemBase> { if (typeof params.title !== 'string') { return; } const qb = Database.knex<MediaItemBase>(this.tableName) .select( '*', Database.knex.raw(`LENGTH(title) - ${params.title.length} AS rank`) ) .where('mediaType', params.mediaType) .where((qb) => qb .where('title', 'LIKE', `%${params.title}%`) .orWhere('originalTitle', 'LIKE', `%${params.title}%`) ) .orderBy('rank', 'asc'); if (params.releaseYear) { qb.whereBetween('releaseDate', [ new Date(params.releaseYear, 0, 1).toISOString(), new Date(params.releaseYear, 11, 31).toISOString(), ]); } return this.deserialize(await qb.first()); } public async findByExactTitle(params: { mediaType: MediaType; title: string; releaseYear?: number; }): Promise<MediaItemBase> { if (typeof params.title !== 'string') { return; } const qb = Database.knex<MediaItemBase>(this.tableName) .where('mediaType', params.mediaType) .where((qb) => qb .where('title', 'LIKE', params.title) .orWhere('originalTitle', 'LIKE', params.title) ); if (params.releaseYear) { qb.whereBetween('releaseDate', [ new Date(params.releaseYear, 0, 1).toISOString(), new Date(params.releaseYear, 11, 31).toISOString(), ]); } return this.deserialize(await qb.first()); } public async itemsToPossiblyUpdate(): Promise<MediaItemBase[]> { return await Database.knex<MediaItemBase>('mediaItem') .select('mediaItem.*') .leftJoin<Seen>('seen', 'seen.mediaItemId', 'mediaItem.id') .leftJoin<ListItem>('listItem', 'listItem.mediaItemId', 'mediaItem.id') .leftJoin<UserRating>( 'userRating', 'userRating.mediaItemId', 'mediaItem.id' ) .where((q) => q .whereNotNull('seen.id') .orWhereNotNull('listItem.id') .orWhereNotNull('userRating.id') ) .whereNot('source', 'user') .whereNot('source', 'goodreads') .groupBy('mediaItem.id'); } public async itemsToNotify(from: Date, to: Date): Promise<MediaItemBase[]> { return await Database.knex<MediaItemBase>(this.tableName) .select('mediaItem.*') .select('notificationsHistory.mediaItemId') .select('notificationsHistory.id AS notificationsHistory.id') .leftJoin<NotificationsHistory>( 'notificationsHistory', 'notificationsHistory.mediaItemId', 'mediaItem.id' ) .whereBetween('mediaItem.releaseDate', [ from.toISOString(), to.toISOString(), ]) .whereNot('mediaType', 'tv') .whereNull('notificationsHistory.id'); } public async episodesToNotify(from: Date, to: Date) { const res = await Database.knex<TvEpisode>('episode') .select(generateColumnNames('episode', tvEpisodeColumns)) .select(generateColumnNames('mediaItem', mediaItemColumns)) .select('notificationsHistory.mediaItemId') .select('notificationsHistory.id AS notificationsHistory.id') .leftJoin<NotificationsHistory>( 'notificationsHistory', 'notificationsHistory.episodeId', 'episode.id' ) .leftJoin<MediaItemBase>('mediaItem', 'mediaItem.id', 'episode.tvShowId') .whereBetween('episode.releaseDate', [ from.toISOString(), to.toISOString(), ]) .where('episode.isSpecialEpisode', false) .whereNull('notificationsHistory.id'); return res.map((row) => _(row) .pickBy((value, column) => column.startsWith('episode.')) .mapKeys((value, key) => key.substring('episode.'.length)) .set( 'tvShow', _(row) .pickBy((value, column) => column.startsWith('mediaItem.')) .mapKeys((value, key) => key.substring('mediaItem.'.length)) .value() ) .value() ) as (TvEpisode & { tvShow: MediaItemBase })[]; } public async lock(mediaItemId: number) { const res = await Database.knex<MediaItemBase>(this.tableName) .update({ lockedAt: new Date().getTime() }) .where('id', mediaItemId) .where('lockedAt', null); if (res === 0) { throw new Error(`MediaItem ${mediaItemId} is locked`); } } public async unlock(mediaItemId: number) { await Database.knex<MediaItemBase>(this.tableName) .update({ lockedAt: null }) .where('id', mediaItemId); } public async mediaItemsWithMissingPosters(mediaItemIdsWithPoster: number[]) { return await Database.knex<MediaItemBase>(this.tableName) .whereNotIn('id', mediaItemIdsWithPoster) .whereNotNull('poster') .whereNot('poster', ''); } public async mediaItemsWithMissingBackdrop( mediaItemIdsWithBackdrop: number[] ) { return await Database.knex<MediaItemBase>(this.tableName) .whereNotIn('id', mediaItemIdsWithBackdrop) .whereNotNull('backdrop') .whereNot('backdrop', ''); } public async mergeSearchResultWithExistingItems( searchResult: MediaItemForProvider[], mediaType: MediaType ) { let idCounter = 0; const searchResultWithId = _.cloneDeep(searchResult).map((item) => ({ ...item, searchResultId: idCounter++, })); const externalIds = _(externalIdColumnNames) .keyBy((id) => id) .mapValues((id) => searchResultWithId.map((mediaItem) => mediaItem[id]).filter(Boolean) ) .value(); const searchResultsByExternalId = _(externalIdColumnNames) .keyBy() .mapValues((value) => _(searchResultWithId) .filter((item) => Boolean(item[value])) .keyBy(value) .value() ) .value(); return await Database.knex.transaction(async (trx) => { const existingItems = ( await trx<MediaItemBase>(this.tableName) .where({ mediaType: mediaType }) .andWhere((qb) => { if (externalIds.tmdbId) { qb.orWhereIn('tmdbId', externalIds.tmdbId); } if (externalIds.imdbId) { qb.orWhereIn('imdbId', externalIds.imdbId); } if (externalIds.tvmazeId) { qb.orWhereIn('tvmazeId', externalIds.tvmazeId); } if (externalIds.igdbId) { qb.orWhereIn('igdbId', externalIds.igdbId); } if (externalIds.openlibraryId) { qb.orWhereIn('openlibraryId', externalIds.openlibraryId); } if (externalIds.audibleId) { qb.orWhereIn('audibleId', externalIds.audibleId); } if (externalIds.goodreadsId) { qb.orWhereIn('goodreadsId', externalIds.goodreadsId); } if (externalIds.traktId) { qb.orWhereIn('traktId', externalIds.traktId); } if (externalIds.tvdbId) { qb.orWhereIn('tvdbId', externalIds.tvdbId); } }) ).map((item) => this.deserialize(item)); const existingSearchResults: (MediaItemItemsResponse & { searchResultId: number; })[] = []; existingItems.forEach((item) => { externalIdColumnNames.forEach((value) => { const res = searchResultsByExternalId[value][item[value]]; if (res) { existingSearchResults.push({ ...res, id: item.id, }); return; } }); }); const existingImages = _( await trx<Image>(imageRepository.tableName) .where({ seasonId: null, }) .whereIn( 'mediaItemId', existingSearchResults.map((value) => value.id) ) ) .groupBy('type') .mapValues((value) => _.keyBy(value, 'mediaItemId')) .value(); for (const item of existingSearchResults) { const slug = mediaItemSlug(item); await trx(this.tableName) .update({ ...this.serialize(this.stripValue(item)), slug: Database.knex.raw( `(CASE WHEN ( ${Database.knex<MediaItemBase>('mediaItem') .count() .where('slug', slug) .whereNot('id', item.id) .toQuery()}) = 0 THEN '${slug}' ELSE '${slug}-${randomSlugId()}' END)` ), }) .where({ id: item.id }); } existingSearchResults.forEach((value) => { const posterId = existingImages.poster && existingImages.poster[value.id]?.id; const backdropId = existingImages.backdrop && existingImages.backdrop[value.id]?.id; value.poster = posterId ? `/img/${posterId}` : null; value.posterSmall = posterId ? `/img/${posterId}?size=small` : null; value.backdrop = backdropId ? `/img/${backdropId}` : null; }); const newItems: MediaItemBase[] = _.differenceBy( searchResultWithId, existingSearchResults, 'searchResultId' ); newItems.forEach((item) => (item.lastTimeUpdated = new Date().getTime())); const newItemsId: { id: number }[] = []; for (const newItem of newItems) { const [res] = await trx<MediaItemBase>(this.tableName) .insert({ ...this.serialize(this.stripValue(newItem)), slug: Database.knex.raw( `(CASE WHEN ( ${Database.knex('mediaItem') .count() .where('slug', mediaItemSlug(newItem)) .toQuery()}) = 0 THEN '${mediaItemSlug(newItem)}' ELSE '${mediaItemSlug(newItem)}-${randomSlugId()}' END)` ), }) .returning<{ id: number }[]>('id'); newItemsId.push(res); } const newItemsWithId = _.merge( newItems, newItemsId ) as (MediaItemItemsResponse & { searchResultId: number; })[]; await Database.knex .batchInsert( imageRepository.tableName, newItemsWithId .filter((item) => item.poster) .map((item) => { const posterId = getImageId(); item.poster = `/img/${posterId}`; item.posterSmall = `/img/${posterId}?size=small`; return { id: posterId, mediaItemId: item.id, seasonId: null, type: 'poster', }; }), 30 ) .transacting(trx) .returning('id'); await Database.knex .batchInsert( imageRepository.tableName, newItemsWithId .filter((item) => item.backdrop) .map((item) => { const backdropId = getImageId(); item.backdrop = `/img/${backdropId}`; return { id: backdropId, mediaItemId: item.id, seasonId: null, type: 'backdrop', }; }), 30 ) .transacting(trx) .returning('id'); return { newItems: _.sortBy(newItemsWithId, 'searchResultId'), existingItems: _.sortBy(existingSearchResults, 'searchResultId'), mergeWithSearchResult: ( existingItems?: (MediaItemItemsResponse & { searchResultId: number; })[] ) => _( _.cloneDeep( _.concat(newItemsWithId, existingItems || existingSearchResults) ) ) .sortBy('searchResultId') .forEach((item) => delete item.searchResultId) .valueOf(), }; }); } public async unlockLockedMediaItems() { return await Database.knex<MediaItemBase>(this.tableName) .update('lockedAt', null) .where('lockedAt', '<=', subDays(new Date(), 1).getTime()); } } export const mediaItemRepository = new MediaItemRepository(); const externalIdColumnNames = <const>[ 'openlibraryId', 'imdbId', 'tmdbId', 'igdbId', 'tvmazeId', 'audibleId', 'traktId', 'goodreadsId', 'tvdbId', ];
the_stack
import { when } from 'jest-when'; import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; import { TransactionList } from '../../src/transaction_list'; import { TransactionPool } from '../../src/transaction_pool'; import { Transaction, Status, TransactionStatus } from '../../src/types'; import { generateRandomPublicKeys } from '../utils/cryptography'; describe('TransactionPool class', () => { let transactionPool: TransactionPool; beforeEach(() => { jest.useFakeTimers(); transactionPool = new TransactionPool({ applyTransactions: jest.fn(), transactionReorganizationInterval: 1, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); jest.spyOn(transactionPool.events, 'emit'); }); describe('constructor', () => { describe('when only applyTransaction is given', () => { it('should set default values', () => { expect((transactionPool as any)._maxTransactions).toEqual(4096); expect((transactionPool as any)._maxTransactionsPerAccount).toEqual(64); expect((transactionPool as any)._minEntranceFeePriority).toEqual(BigInt(0)); expect((transactionPool as any)._minReplacementFeeDifference).toEqual(BigInt(10)); expect((transactionPool as any)._transactionExpiryTime).toEqual(3 * 60 * 60 * 1000); }); }); describe('when all the config properties are given', () => { it('should set the value to given option values', () => { transactionPool = new TransactionPool({ applyTransactions: jest.fn(), maxTransactions: 2048, maxTransactionsPerAccount: 32, minReplacementFeeDifference: BigInt(100), minEntranceFeePriority: BigInt(10), transactionExpiryTime: 60 * 60 * 1000, // 1 hours in ms baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); expect((transactionPool as any)._maxTransactions).toEqual(2048); expect((transactionPool as any)._maxTransactionsPerAccount).toEqual(32); expect((transactionPool as any)._minEntranceFeePriority).toEqual(BigInt(10)); expect((transactionPool as any)._minReplacementFeeDifference).toEqual(BigInt(100)); expect((transactionPool as any)._transactionExpiryTime).toEqual(60 * 60 * 1000); }); }); }); describe('get', () => { let txGetBytesStub: jest.Mock; let tx: Transaction; beforeEach(async () => { tx = { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; txGetBytesStub = jest.fn(); tx.getBytes = txGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); await transactionPool.add(tx); }); it('should return transaction if exist', () => { expect(transactionPool.get(Buffer.from('1'))).toEqual(tx); }); it('should return undefined if it does not exist', () => { expect(transactionPool.get(Buffer.from('2'))).toBeUndefined(); }); }); describe('contains', () => { let txGetBytesStub: jest.Mock; let tx: Transaction; beforeEach(async () => { tx = { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; txGetBytesStub = jest.fn(); tx.getBytes = txGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); await transactionPool.add(tx); }); it('should return transaction if exist', () => { expect(transactionPool.contains(Buffer.from('1'))).toBe(true); }); it('should return undefined if it does not exist', () => { expect(transactionPool.contains(Buffer.from('2'))).toBe(false); }); }); describe('getProcessableTransactions', () => { let senderPublicKeys: Buffer[]; beforeEach(async () => { senderPublicKeys = generateRandomPublicKeys(3); const txs = [ { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKeys[0], }, { id: Buffer.from('2'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(30000), senderPublicKey: senderPublicKeys[0], }, { id: Buffer.from('9'), moduleID: 3, assetID: 0, nonce: BigInt(9), minFee: BigInt(10), fee: BigInt(30000), senderPublicKey: senderPublicKeys[0], }, { id: Buffer.from('3'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKeys[1], }, { id: Buffer.from('10'), moduleID: 3, assetID: 0, nonce: BigInt(100), fee: BigInt(30000), senderPublicKey: senderPublicKeys[2], }, ] as Transaction[]; for (const tx of txs) { tx.getBytes = jest.fn().mockReturnValue(Buffer.from(new Array(10))); await transactionPool.add(tx); } (transactionPool as any)._transactionList .get(getAddressFromPublicKey(senderPublicKeys[0])) .promote([txs[0]]); (transactionPool as any)._transactionList .get(getAddressFromPublicKey(senderPublicKeys[1])) .promote([txs[3]]); // Force to make it unprocessable (transactionPool['_transactionList'].get( getAddressFromPublicKey(senderPublicKeys[2]), ) as TransactionList)['_demoteAfter'](BigInt(0)); }); it('should return copy of processable transactions list', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender0 = processableTransactions.get( getAddressFromPublicKey(senderPublicKeys[0]), ); const transactionFromSender1 = processableTransactions.get( getAddressFromPublicKey(senderPublicKeys[1]), ); expect(transactionFromSender0).toHaveLength(1); expect((transactionFromSender0 as Transaction[])[0].nonce.toString()).toEqual('1'); expect(transactionFromSender1).toHaveLength(1); expect((transactionFromSender1 as Transaction[])[0].nonce.toString()).toEqual('1'); // Check if it is a copy processableTransactions.delete(getAddressFromPublicKey(senderPublicKeys[0])); (processableTransactions as any).get(getAddressFromPublicKey(senderPublicKeys[1]))[0] = 'random thing'; expect( (transactionPool as any)._transactionList.get(getAddressFromPublicKey(senderPublicKeys[0])), ).not.toBeUndefined(); expect( transactionPool .getProcessableTransactions() .get(getAddressFromPublicKey(senderPublicKeys[1])), ).toHaveLength(1); }); it('should not include the sender key if processable transactions are empty', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender2 = processableTransactions.get( getAddressFromPublicKey(senderPublicKeys[2]), ); expect(transactionFromSender2).toBeUndefined(); }); }); describe('add', () => { let txGetBytesStub: any; const tx = { id: Buffer.from('1'), nonce: BigInt(1), moduleID: 3, assetID: 0, fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; txGetBytesStub = jest.fn(); tx.getBytes = txGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); it('should add a valid transaction to the transaction list as processable', async () => { // Act const { status } = await transactionPool.add(tx); // Arrange & Assert expect(status).toEqual(Status.OK); expect(transactionPool['_allTransactions'].has(Buffer.from('1'))).toEqual(true); const originalTrxObj = transactionPool['_transactionList'] .get(getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getProcessable()).toContain(originalTrxObj); }); it('should add a valid higher nonce transaction to the transaction list as unprocessable', async () => { // Arrange (transactionPool['_applyFunction'] as jest.Mock).mockRejectedValue({ code: 'ERR_TRANSACTION_VERIFICATION_FAIL', transactionError: { code: 'ERR_NONCE_OUT_OF_BOUNDS', actual: '123', expected: '2' }, }); // Act const { status } = await transactionPool.add(tx); // Assert expect(status).toEqual(Status.OK); expect(transactionPool['_allTransactions'].has(Buffer.from('1'))).toEqual(true); const originalTrxObj = transactionPool['_transactionList'] .get(getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getUnprocessable()).toContain(originalTrxObj); }); it('should reject a duplicate transaction', async () => { // Arrange const txDuplicate = { ...tx }; // Act const { status: status1 } = await transactionPool.add(tx); const { status: status2 } = await transactionPool.add(txDuplicate); // Assert expect(status1).toEqual(Status.OK); expect(status2).toEqual(Status.OK); // Check if its not added to the transaction list expect(Object.keys(transactionPool['_allTransactions'])).toHaveLength(1); }); it('should throw when a transaction is invalid', async () => { // Arrange jest.spyOn(transactionPool, '_getStatus' as any); (transactionPool['_applyFunction'] as jest.Mock).mockRejectedValue( new Error('Invalid transaction'), ); // Act const result = await transactionPool.add(tx); // Assert expect(transactionPool['_getStatus']).toHaveReturnedWith(TransactionStatus.INVALID); expect(result.status).toEqual(Status.FAIL); expect(result.error?.message).toEqual('Invalid transaction'); }); it('should throw when a transaction is invalid but not include higher nonce error', async () => { // Arrange jest.spyOn(transactionPool, '_getStatus' as any); (transactionPool['_applyFunction'] as jest.Mock).mockRejectedValue( new Error('Invalid transaction'), ); // Act const result = await transactionPool.add(tx); // Assert expect(transactionPool['_getStatus']).toHaveReturnedWith(TransactionStatus.INVALID); expect(result.status).toEqual(Status.FAIL); expect(result.error?.message).toEqual('Invalid transaction'); }); it('should reject a transaction with lower fee than minEntranceFee', async () => { // Arrange transactionPool = new TransactionPool({ applyTransactions: jest.fn(), minEntranceFeePriority: BigInt(10), baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); const lowFeeTrx = { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(3000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; const tempTxGetBytesStub = jest.fn(); lowFeeTrx.getBytes = tempTxGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); // Act const { status } = await transactionPool.add(lowFeeTrx); // Assert expect(status).toEqual(Status.FAIL); }); it('should evict lowest feePriority among highest nonce trx from the pool when txPool is full and all the trxs are processable', async () => { // Arrange const MAX_TRANSACTIONS = 10; transactionPool = new TransactionPool({ applyTransactions: jest.fn(), minEntranceFeePriority: BigInt(10), maxTransactions: MAX_TRANSACTIONS, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); const tempApplyTransactionsStub = jest.fn(); (transactionPool as any)._applyFunction = tempApplyTransactionsStub; txGetBytesStub = jest.fn(); for (let i = 0; i < MAX_TRANSACTIONS; i += 1) { const tempTx = { id: Buffer.from(`${i.toString()}`), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; tempTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS + i)), ); tempApplyTransactionsStub.mockResolvedValue([{ status: Status.OK, errors: [] }]); await transactionPool.add(tempTx); } expect(transactionPool.getAll()).toHaveLength(MAX_TRANSACTIONS); const highFeePriorityTx = { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(50000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; highFeePriorityTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS)), ); tempApplyTransactionsStub.mockResolvedValue([{ status: Status.OK, errors: [] }]); jest.spyOn(transactionPool, '_evictProcessable' as any); // Act const { status } = await transactionPool.add(highFeePriorityTx); // Assert expect(transactionPool['_evictProcessable']).toHaveBeenCalledTimes(1); expect(status).toEqual(Status.OK); }); it('should evict the unprocessable trx with the lowest feePriority from the pool when txPool is full and not all trxs are processable', async () => { const MAX_TRANSACTIONS = 10; transactionPool = new TransactionPool({ applyTransactions: jest.fn(), minEntranceFeePriority: BigInt(10), maxTransactions: MAX_TRANSACTIONS, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); const tempApplyTransactionsStub = jest.fn(); (transactionPool as any)._applyFunction = tempApplyTransactionsStub; txGetBytesStub = jest.fn(); for (let i = 0; i < MAX_TRANSACTIONS - 1; i += 1) { const tempTx = { id: Buffer.from(`${i.toString()}`), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; tempTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS + i)), ); await transactionPool.add(tempTx); } const nonSequentialTx = { id: Buffer.from('21'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; nonSequentialTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS)), ); tempApplyTransactionsStub.mockRejectedValue({ code: 'ERR_TRANSACTION_VERIFICATION_FAIL', transactionError: { code: 'ERR_NONCE_OUT_OF_BOUNDS' }, }); await transactionPool.add(nonSequentialTx); expect(transactionPool.getAll()).toContain(nonSequentialTx); expect(transactionPool.getAll()).toHaveLength(MAX_TRANSACTIONS); const highFeePriorityTx = { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(50000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; highFeePriorityTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS)), ); tempApplyTransactionsStub.mockResolvedValue([{ status: Status.OK, errors: [] }]); jest.spyOn(transactionPool, '_evictUnprocessable' as any); const { status } = await transactionPool.add(highFeePriorityTx); expect(transactionPool.getAll()).not.toContain(nonSequentialTx); expect(transactionPool['_evictUnprocessable']).toHaveBeenCalledTimes(1); expect(status).toEqual(Status.OK); }); it('should reject a transaction with a lower feePriority than the lowest feePriority present in TxPool', async () => { const MAX_TRANSACTIONS = 10; transactionPool = new TransactionPool({ applyTransactions: jest.fn(), minEntranceFeePriority: BigInt(10), maxTransactions: MAX_TRANSACTIONS, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); const tempApplyTransactionsStub = jest.fn(); (transactionPool as any)._applyFunction = tempApplyTransactionsStub; txGetBytesStub = jest.fn(); for (let i = 0; i < MAX_TRANSACTIONS; i += 1) { const tempTx = { id: Buffer.from(`${i.toString()}`), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; tempTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(MAX_TRANSACTIONS + i)), ); await transactionPool.add(tempTx); } expect(transactionPool.getAll()).toHaveLength(MAX_TRANSACTIONS); const lowFeePriorityTx = { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(1000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; lowFeePriorityTx.getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(2 * MAX_TRANSACTIONS)), ); tempApplyTransactionsStub.mockResolvedValue([{ status: Status.OK, errors: [] }]); const { status } = await transactionPool.add(lowFeePriorityTx); expect(status).toEqual(Status.FAIL); }); }); describe('remove', () => { let txGetBytesStub: any; const senderPublicKey = generateRandomPublicKeys()[0]; const tx = { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey, } as Transaction; const additionalTx = { id: Buffer.from('2'), moduleID: 3, assetID: 0, nonce: BigInt(3), fee: BigInt(30000), senderPublicKey, } as Transaction; // eslint-disable-next-line prefer-const txGetBytesStub = jest.fn().mockReturnValue(Buffer.from(new Array(10))); tx.getBytes = txGetBytesStub; additionalTx.getBytes = txGetBytesStub; beforeEach(async () => { await transactionPool.add(tx); await transactionPool.add(additionalTx); }); afterEach(() => { transactionPool.remove(tx); transactionPool.remove(additionalTx); }); it('should return false when a tx id does not exist', () => { expect( transactionPool['_transactionList'] .get(getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); // Remove a transaction that does not exist const nonExistentTrx = { id: Buffer.from('155'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(1000), senderPublicKey: generateRandomPublicKeys()[0], } as Transaction; const removeStatus = transactionPool.remove(nonExistentTrx); expect(removeStatus).toEqual(false); }); it('should remove the transaction from _allTransactions, _transactionList and _feePriorityQueue', () => { expect( transactionPool['_transactionList'] .get(getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); // Remove the above transaction const removeStatus = transactionPool.remove(tx); expect(removeStatus).toEqual(true); expect(transactionPool.getAll()).toHaveLength(1); expect( transactionPool['_transactionList'] .get(getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toBeUndefined(); expect(transactionPool['_feePriorityQueue'].values).not.toContain(tx.id); }); it('should remove the transaction list key if the list is empty', () => { transactionPool.remove(tx); transactionPool.remove(additionalTx); expect( transactionPool['_transactionList'].get(getAddressFromPublicKey(tx.senderPublicKey)), ).toBeUndefined(); }); }); describe('evictUnprocessable', () => { const senderPublicKey = generateRandomPublicKeys()[0]; const transactions = [ { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(20000), senderPublicKey, } as Transaction, { id: Buffer.from('3'), moduleID: 3, assetID: 0, nonce: BigInt(3), fee: BigInt(30000), senderPublicKey, } as Transaction, ]; let txGetBytesStub: any; // eslint-disable-next-line prefer-const txGetBytesStub = jest.fn(); transactions[0].getBytes = txGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); transactions[1].getBytes = txGetBytesStub.mockReturnValue(Buffer.from(new Array(10))); beforeEach(async () => { transactionPool = new TransactionPool({ applyTransactions: jest.fn().mockResolvedValue([{ status: Status.OK, errors: [] }]), transactionReorganizationInterval: 1, maxTransactions: 2, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); jest.spyOn(transactionPool.events, 'emit'); await transactionPool.add(transactions[0]); await transactionPool.add(transactions[1]); }); afterEach(() => { transactionPool.remove(transactions[0]); transactionPool.remove(transactions[1]); }); it('should evict unprocessable transaction with lowest fee', () => { const isEvicted = (transactionPool as any)._evictUnprocessable(); expect(isEvicted).toBe(true); expect((transactionPool as any)._allTransactions).not.toContain(transactions[0]); expect(transactionPool.events.emit).toHaveBeenCalledTimes(1); }); }); describe('evictProcessable', () => { const senderPublicKey1 = generateRandomPublicKeys()[0]; const senderPublicKey2 = generateRandomPublicKeys()[0]; const transactionsFromSender1 = [ { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKey1, } as Transaction, { id: Buffer.from('2'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(60000), senderPublicKey: senderPublicKey1, } as Transaction, ]; const transactionsFromSender2 = [ { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKey2, } as Transaction, { id: Buffer.from('12'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(30000), senderPublicKey: senderPublicKey2, } as Transaction, ]; const higherNonceTrxs = [transactionsFromSender1[1], transactionsFromSender2[1]]; let txGetBytesStub: any; // eslint-disable-next-line prefer-const txGetBytesStub = jest.fn(); transactionsFromSender1[0].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender1[1].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender2[0].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender2[1].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); beforeEach(async () => { transactionPool = new TransactionPool({ applyTransactions: jest.fn().mockResolvedValue([{ status: Status.OK, errors: [] }]), transactionReorganizationInterval: 1, maxTransactions: 2, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); jest.spyOn(transactionPool.events, 'emit'); await transactionPool.add(transactionsFromSender1[0]); await transactionPool.add(transactionsFromSender1[1]); await transactionPool.add(transactionsFromSender2[0]); await transactionPool.add(transactionsFromSender2[1]); }); afterEach(() => { transactionPool.remove(transactionsFromSender1[0]); transactionPool.remove(transactionsFromSender1[1]); transactionPool.remove(transactionsFromSender2[0]); transactionPool.remove(transactionsFromSender2[1]); }); it('should evict processable transaction with lowest fee', () => { const isEvicted = (transactionPool as any)._evictProcessable(); expect(isEvicted).toBe(true); expect((transactionPool as any)._allTransactions).not.toContain(transactionsFromSender2[1]); // To check if evicted processable transaction is the higher nonce transaction of an account expect(higherNonceTrxs).toContain(transactionsFromSender2[1]); expect(transactionPool.events.emit).toHaveBeenCalledTimes(1); }); }); describe('reorganize', () => { const senderPublicKey1 = generateRandomPublicKeys()[0]; const senderPublicKey2 = generateRandomPublicKeys()[0]; const transactionsFromSender1 = [ { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKey1, } as Transaction, { id: Buffer.from('2'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(60000), senderPublicKey: senderPublicKey1, } as Transaction, { id: Buffer.from('3'), moduleID: 3, assetID: 0, nonce: BigInt(3), fee: BigInt(90000), senderPublicKey: senderPublicKey1, } as Transaction, ]; const transactionsFromSender2 = [ { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(30000), senderPublicKey: senderPublicKey2, } as Transaction, ]; let txGetBytesStub: any; // eslint-disable-next-line prefer-const txGetBytesStub = jest.fn(); transactionsFromSender1[0].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender1[1].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender1[2].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); transactionsFromSender2[0].getBytes = txGetBytesStub.mockReturnValue( Buffer.from(new Array(10)), ); let address: Buffer; let txList: TransactionList; beforeEach(async () => { transactionPool = new TransactionPool({ applyTransactions: jest.fn(), transactionReorganizationInterval: 1, baseFees: [ { assetID: 0, baseFee: BigInt(1), moduleID: 3, }, ], minFeePerByte: 1000, }); await transactionPool.add(transactionsFromSender1[0]); await transactionPool.add(transactionsFromSender1[1]); await transactionPool.add(transactionsFromSender1[2]); await transactionPool.add(transactionsFromSender2[0]); // eslint-disable-next-line prefer-destructuring address = (transactionPool as any)._transactionList.values()[0].address; txList = (transactionPool as any)._transactionList.get(address); // eslint-disable-next-line @typescript-eslint/no-floating-promises transactionPool.start(); }); afterEach(() => { transactionPool.remove(transactionsFromSender1[0]); transactionPool.remove(transactionsFromSender1[1]); transactionPool.remove(transactionsFromSender1[2]); transactionPool.remove(transactionsFromSender2[0]); transactionPool.stop(); }); it('should not promote unprocessable transactions to processable transactions', () => { transactionPool.remove(transactionsFromSender1[1]); jest.advanceTimersByTime(2); const unprocessableTransactions = txList.getUnprocessable(); expect(unprocessableTransactions).toContain(transactionsFromSender1[2]); }); it('should call apply function with processable transaction', () => { // First transaction is processable jest.advanceTimersByTime(2); expect(transactionPool['_applyFunction']).toHaveBeenCalledWith(transactionsFromSender1); expect(transactionPool['_applyFunction']).toHaveBeenCalledWith(transactionsFromSender2); }); it('should not remove unprocessable transaction but also does not promote', () => { // Arrange when(transactionPool['_applyFunction'] as jest.Mock) .calledWith(transactionsFromSender1) .mockRejectedValue({ id: Buffer.from('2'), code: 'ERR_TRANSACTION_VERIFICATION_FAIL', transactionError: { code: 'ERR_NONCE_OUT_OF_BOUNDS', }, } as never); jest.advanceTimersByTime(2); // Assert expect( transactionPool['_allTransactions'].get(transactionsFromSender1[0].id), ).not.toBeUndefined(); // Unprocessable trx should not be removed expect( transactionPool['_allTransactions'].get(transactionsFromSender1[1].id), ).not.toBeUndefined(); expect( transactionPool['_allTransactions'].get(transactionsFromSender1[2].id), ).not.toBeUndefined(); // Unprocessable trx should not be promoted expect( transactionPool .getProcessableTransactions() .get(address) ?.map(tx => tx.id), ).not.toContain(transactionsFromSender1[1].id); expect( transactionPool .getProcessableTransactions() .get(address) ?.map(tx => tx.id), ).not.toContain(transactionsFromSender1[2].id); }); }); describe('expire', () => { const senderPublicKey1 = generateRandomPublicKeys()[0]; const senderPublicKey2 = generateRandomPublicKeys()[1]; const transactionsForSender1 = [ { id: Buffer.from('1'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(1000), senderPublicKey: senderPublicKey1, receivedAt: new Date(0), } as Transaction, { id: Buffer.from('2'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(2000), senderPublicKey: senderPublicKey1, receivedAt: new Date(), } as Transaction, { id: Buffer.from('3'), moduleID: 3, assetID: 0, nonce: BigInt(3), fee: BigInt(3000), senderPublicKey: senderPublicKey1, receivedAt: new Date(0), } as Transaction, ]; const transactionsForSender2 = [ { id: Buffer.from('11'), moduleID: 3, assetID: 0, nonce: BigInt(1), fee: BigInt(1000), senderPublicKey: senderPublicKey2, receivedAt: new Date(0), } as Transaction, { id: Buffer.from('12'), moduleID: 3, assetID: 0, nonce: BigInt(2), fee: BigInt(2000), senderPublicKey: senderPublicKey2, receivedAt: new Date(), } as Transaction, ]; beforeEach(() => { transactionPool['_allTransactions'].set( transactionsForSender1[0].id, transactionsForSender1[0], ); transactionPool['_allTransactions'].set( transactionsForSender1[1].id, transactionsForSender1[1], ); transactionPool['_allTransactions'].set( transactionsForSender1[2].id, transactionsForSender1[2], ); transactionPool['_allTransactions'].set( transactionsForSender2[0].id, transactionsForSender2[0], ); transactionPool['_allTransactions'].set( transactionsForSender2[1].id, transactionsForSender2[1], ); }); it('should expire old transactions', () => { (transactionPool as any).remove = jest.fn().mockReturnValue(true); (transactionPool as any)._expire(); expect((transactionPool as any).remove).toHaveBeenCalledWith(transactionsForSender1[0]); expect((transactionPool as any).remove).toHaveBeenCalledWith(transactionsForSender1[2]); expect((transactionPool as any).remove).toHaveBeenCalledWith(transactionsForSender2[0]); expect(transactionPool.events.emit).toHaveBeenCalledTimes(3); }); }); });
the_stack
import { assert, expect } from "chai"; import * as enzyme from "enzyme"; import * as React from "react"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { BackgroundMapSettings, DisplayStyle3dSettings, EmptyLocalization, PlanarClipMaskMode, PlanarClipMaskPriority, TerrainHeightOriginMode, TerrainSettings, } from "@itwin/core-common"; import { DisplayStyle3dState, IModelConnection, MockRender, ScreenViewport, ViewState3d } from "@itwin/core-frontend"; import { SpecialKey } from "@itwin/appui-abstract"; import { NumberInput } from "@itwin/core-react"; import { Select, ToggleSwitch } from "@itwin/itwinui-react"; import { SourceMapContext } from "../ui/widget/MapLayerManager"; import { MapManagerSettings } from "../ui/widget/MapManagerSettings"; import { TestUtils } from "./TestUtils"; import { QuantityNumberInput } from "@itwin/imodel-components-react"; describe("MapManagerSettings", () => { const viewportMock = moq.Mock.ofType<ScreenViewport>(); const viewMock = moq.Mock.ofType<ViewState3d>(); const displayStyleMock = moq.Mock.ofType<DisplayStyle3dState>(); const imodelMock = moq.Mock.ofType<IModelConnection>(); const displayStyleSettingsMock = moq.Mock.ofType<DisplayStyle3dSettings>(); const backgroundMapSettingsMock = moq.Mock.ofType<BackgroundMapSettings>(); const terrainSettingsMock = moq.Mock.ofType<TerrainSettings>(); // Utility methods that give the index of components rendered by // MapManagerSettings. // Any re-ordering inside the component render will invalidate // this and will need to be revisited. const getToggleIndex = (toggleName: string) => { switch (toggleName) { case "locatable": return 0; case "mask": return 1; case "overrideMaskTransparency": return 2; case "depthBuffer": return 3; case "terrain": return 4; } assert.fail("invalid name provided."); return 0; }; const getQuantityNumericInputIndex = (name: string) => { switch (name) { case "groundBias": return 0; case "terrainOrigin": return 1; } assert.fail("invalid name provided."); return 0; }; const changeNumericInputValue = (component: any, value: number) => { // For some reasons could not get 'simulate' and 'change' to work here, so calling directly the onChange prop instead. component.find("input").props().onChange!({ currentTarget: { value } } as any); // Handler is not triggered until there is a key press component.find("input").simulate("keydown", { key: SpecialKey.Enter }); component.update(); }; before(async () => { await MockRender.App.startup({localization: new EmptyLocalization()}); await TestUtils.initialize(); }); after(async () => { await MockRender.App.shutdown(); TestUtils.terminateUiComponents(); }); beforeEach(() => { terrainSettingsMock.reset(); terrainSettingsMock.setup((ts) => ts.heightOriginMode).returns(() => TerrainHeightOriginMode.Geodetic); terrainSettingsMock.setup((ts) => ts.heightOrigin).returns(() => 0); terrainSettingsMock.setup((ts) => ts.exaggeration).returns(() => 0); backgroundMapSettingsMock.reset(); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.groundBias).returns(() => 0); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.transparency).returns(() => 0); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.applyTerrain).returns(() => false); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.terrainSettings).returns(() => terrainSettingsMock.object); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.useDepthBuffer).returns(() => false); backgroundMapSettingsMock.setup((bgMapSettings) => bgMapSettings.locatable).returns(() => true); displayStyleSettingsMock.reset(); displayStyleSettingsMock.setup((styleSettings) => styleSettings.backgroundMap).returns(() => backgroundMapSettingsMock.object); displayStyleMock.reset(); displayStyleMock.setup((ds) => ds.attachMapLayerSettings(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())); displayStyleMock.setup((style) => style.attachMapLayerSettings(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())); displayStyleMock.setup((style) => style.settings).returns(() => displayStyleSettingsMock.object); viewMock.reset(); viewMock.setup((view) => view.iModel).returns(() => imodelMock.object); viewMock.setup((x) => x.getDisplayStyle3d()).returns(() => displayStyleMock.object); viewportMock.reset(); viewportMock.setup((viewport) => viewport.view).returns(() => viewMock.object); viewportMock.setup((viewport) => viewport.changeBackgroundMapProps(moq.It.isAny())); viewportMock.setup((viewport) => viewport.invalidateRenderPlan()); }); const refreshFromStyle = sinon.spy(); const mountComponent = () => { return enzyme.mount( <SourceMapContext.Provider value={{ activeViewport: viewportMock.object, loadingSources: false, sources: [], bases: [], refreshFromStyle, }}> <MapManagerSettings /> </SourceMapContext.Provider>); }; it("renders", () => { const wrapper = mountComponent(); wrapper.unmount(); }); it("Terrain toggle", () => { const component = mountComponent(); const quantityNumericInputs = component.find(QuantityNumberInput); // Make sure groundBias is NOT disabled // Note: Ideally I would use a CSS selector instead of searching html, but could not find any that would work. expect(quantityNumericInputs.at(getQuantityNumericInputIndex("groundBias")).find("input").html().includes("disabled")).to.be.false; // terrainOrigin is disabled initially expect(quantityNumericInputs.at(getQuantityNumericInputIndex("terrainOrigin")).find("input").html().includes("disabled")).to.be.true; // exaggeration is disabled initially const numericInputs = component.find(NumberInput); expect(numericInputs.at(0).find("input").html().includes("disabled")).to.be.true; // Make sure the 'useDepthBuffer' toggle is NOT disabled let toggles = component.find(ToggleSwitch); // Elevation type should be disabled initially let select = component.find(Select); expect(select.props().disabled).to.be.true; expect(toggles.at(getToggleIndex("depthBuffer")).find(".iui-disabled").exists()).to.be.false; // 'changeBackgroundMapProps' should not have been called before terrain is toggled viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // Toggle 'enable' terrain toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); component.update(); // 'changeBackgroundMapProps' should have been called once now viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.once()); // 'useDepthBuffer' toggle should now be disabled toggles = component.find(ToggleSwitch); expect(toggles.at(getToggleIndex("depthBuffer")).find(".iui-disabled").exists()).to.be.true; const quantityInputs = component.find(QuantityNumberInput); // Make sure groundBias is now disabled expect(quantityInputs.at(getQuantityNumericInputIndex("groundBias")).find("input").html().includes("disabled")).to.be.true; // terrainOrigin and exaggeration should be enable after terrain was toggled expect(quantityInputs.at(getQuantityNumericInputIndex("terrainOrigin")).find("input").html().includes("disabled")).to.be.false; // terrainOrigin and exaggeration should be enable after terrain was toggled expect(numericInputs.at(0).find("input").html().includes("disabled")).to.be.false; // Elevation type should be enabled select = component.find(Select); expect(select.props().disabled).to.be.false; component.unmount(); }); it("Transparency slider", () => { viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); const component = mountComponent(); const sliders = component.find(".iui-slider-thumb"); sliders.at(0).simulate("keydown", { key: SpecialKey.ArrowRight }); viewportMock.verify((x) => x.changeBackgroundMapProps({ transparency: 0.01 }), moq.Times.once()); component.unmount(); }); it("Mask Transparency slider", () => { viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); const component = mountComponent(); let sliders = component.find(".iui-slider-thumb"); // Make sure the slider is disabled by default expect(sliders.at(1).props()["aria-disabled"]).to.be.true; // Turn on the mask toggle const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("mask")).find("input").simulate("change", {target: { checked: true }}); toggles.at(getToggleIndex("overrideMaskTransparency")).find("input").simulate("change", {target: { checked: true }}); component.update(); // Make sure the slider is now enabled sliders = component.find(".iui-slider-thumb"); expect(sliders.at(1).props()["aria-disabled"]).to.be.false; sliders.at(0).simulate("keydown", { key: SpecialKey.ArrowUp }); viewportMock.verify((x) => x.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.Priority, priority: PlanarClipMaskPriority.BackgroundMap, transparency: 0 } }), moq.Times.once()); component.unmount(); }); it("Locatable toggle", () => { const component = mountComponent(); const toggles = component.find(ToggleSwitch); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); toggles.at(getToggleIndex("locatable")).find("input").simulate("change", {target: { checked: false }}); component.update(); // 'changeBackgroundMapProps' should have been called once now viewportMock.verify((x) => x.changeBackgroundMapProps({ nonLocatable: true }), moq.Times.once()); component.unmount(); }); it("Mask toggle", () => { const component = mountComponent(); const toggles = component.find(ToggleSwitch); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); toggles.at(getToggleIndex("mask")).find("input").simulate("change", {target: { checked: true }}); component.update(); // 'changeBackgroundMapProps' should have been called once now viewportMock.verify((x) => x.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.Priority, priority: PlanarClipMaskPriority.BackgroundMap, transparency: undefined } }), moq.Times.once()); toggles.at(getToggleIndex("mask")).find("input").simulate("change", {target: { checked: false }}); component.update(); viewportMock.verify((x) => x.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.None } }), moq.Times.once()); component.unmount(); }); it("Override Mask Transparency Toggle", () => { viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); const component = mountComponent(); let toggles = component.find(ToggleSwitch); // By default, the toggle should be disabled expect(toggles.at(getToggleIndex("overrideMaskTransparency")).find(".iui-disabled").exists()).to.be.true; // First turn ON the masking toggle toggles.at(getToggleIndex("mask")).find("input").simulate("change", {target: { checked: true }}); component.update(); toggles = component.find(ToggleSwitch); // Toggle should be enabled now expect(toggles.at(getToggleIndex("overrideMaskTransparency")).find(".iui-disabled").exists()).to.be.false; // .. then we can turn ON the override mask transparency toggles.at(getToggleIndex("overrideMaskTransparency")).find("input").simulate("change", {target: { checked: true }}); component.update(); // 'changeBackgroundMapProps' should have been called once now viewportMock.verify((x) => x.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.Priority, priority: PlanarClipMaskPriority.BackgroundMap, transparency: 0 } }), moq.Times.once()); // turn if OFF again toggles.at(getToggleIndex("overrideMaskTransparency")).find("input").simulate("change", {target: { checked: false }}); component.update(); viewportMock.verify((x) => x.changeBackgroundMapProps({ planarClipMask: { mode: PlanarClipMaskMode.Priority, priority: PlanarClipMaskPriority.BackgroundMap, transparency: undefined } }), moq.Times.exactly(2)); component.unmount(); }); it("ground bias", () => { const component = mountComponent(); const numericInputs = component.find(QuantityNumberInput); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); const oneStepIncrementValue = 1; // 1 foot const oneStepFiredValue = oneStepIncrementValue*0.3048; // .. in meters changeNumericInputValue(numericInputs.at(getQuantityNumericInputIndex("groundBias")), oneStepIncrementValue); viewportMock.verify((x) => x.changeBackgroundMapProps({ groundBias: oneStepFiredValue }), moq.Times.once()); component.unmount(); }); it("terrainOrigin", () => { const component = mountComponent(); const numericInputs = component.find(QuantityNumberInput); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // turn on the 'terrain' toggle then change the input value const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); const oneStepIncrementValue = 1; // 1 foot const oneStepFiredValue = oneStepIncrementValue*0.3048; // .. in meters changeNumericInputValue(numericInputs.at(getQuantityNumericInputIndex("terrainOrigin")), oneStepIncrementValue); viewportMock.verify((x) => x.changeBackgroundMapProps({ terrainSettings: { heightOrigin: oneStepFiredValue } }), moq.Times.once()); component.unmount(); }); it("exaggeration", () => { const component = mountComponent(); const numericInputs = component.find(NumberInput); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // turn ON the 'terrain' toggle then change the input value const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); changeNumericInputValue(numericInputs.at(0), 1); viewportMock.verify((x) => x.changeBackgroundMapProps({ terrainSettings: { exaggeration: 1 } }), moq.Times.once()); component.unmount(); }); it("heightOriginMode geoid", () => { const component = mountComponent(); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // turn ON the 'terrain' toggle then change the combo box value const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); const select = component.find(Select); select.props().onChange!("geoid"); viewportMock.verify((x) => x.changeBackgroundMapProps({ terrainSettings: { heightOriginMode: TerrainHeightOriginMode.Geoid } }), moq.Times.once()); component.unmount(); }); it("heightOriginMode geodetic", () => { const component = mountComponent(); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // turn ON the 'terrain' toggle then change the combo box value const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); const select = component.find(Select); select.props().onChange!("geodetic"); viewportMock.verify((x) => x.changeBackgroundMapProps({ terrainSettings: { heightOriginMode: TerrainHeightOriginMode.Geodetic } }), moq.Times.once()); component.unmount(); }); it("heightOriginMode ground", () => { const component = mountComponent(); viewportMock.verify((x) => x.changeBackgroundMapProps(moq.It.isAny()), moq.Times.never()); // turn ON the 'terrain' toggle then change the combo box value const toggles = component.find(ToggleSwitch); toggles.at(getToggleIndex("terrain")).find("input").simulate("change", {target: { checked: true }}); const select = component.find(Select); select.props().onChange!("ground"); viewportMock.verify((x) => x.changeBackgroundMapProps({ terrainSettings: { heightOriginMode: TerrainHeightOriginMode.Ground } }), moq.Times.once()); component.unmount(); }); });
the_stack
import { Database, makeArray, Logger, Schema, Context, Query, Model, TableType, union, difference } from 'koishi' import { executeUpdate } from '@koishijs/orm-utils' import { Builder, Caster } from '@koishijs/sql-utils' import sqlite, { Statement } from 'better-sqlite3' import { resolve } from 'path' import { escape as sqlEscape, escapeId, format } from 'sqlstring-sqlite' import { stat } from 'fs/promises' declare module 'koishi' { interface Database { sqlite: SQLiteDatabase } interface Modules { 'database-sqlite': typeof import('.') } } const logger = new Logger('sqlite') function getTypeDefinition({ type }: Model.Field) { switch (type) { case 'integer': case 'unsigned': case 'date': case 'time': case 'timestamp': return `INTEGER` case 'float': case 'double': case 'decimal': return `REAL` case 'char': case 'string': case 'text': case 'list': case 'json': return `TEXT` } } export interface ISQLiteFieldInfo { name: string type: string notnull: number // eslint-disable-next-line @typescript-eslint/naming-convention dflt_value: string pk: boolean } class SQLiteDatabase extends Database { public db: sqlite.Database sqlite = this sql: Builder caster: Caster #path: string constructor(public ctx: Context, public config: SQLiteDatabase.Config) { super(ctx) this.#path = this.config.path === ':memory:' ? this.config.path : resolve(ctx.app.options.baseDir, this.config.path) this.sql = new class extends Builder { format = format escapeId = escapeId escape(value: any) { if (value instanceof Date) { return (+value) + '' } return sqlEscape(value) } protected createElementQuery(key: string, value: any) { return `(',' || ${key} || ',') LIKE '%,${this.escape(value)},%'` } }() this.caster = new Caster(ctx.model) this.caster.register<object, string>({ types: ['json'], dump: value => JSON.stringify(value), load: (value, initial) => value ? JSON.parse(value) : initial, }) this.caster.register<string[], string>({ types: ['list'], dump: value => value.join(','), load: (value) => value ? value.split(',') : [], }) this.caster.register<Date, number>({ types: ['date', 'time', 'timestamp'], dump: value => +value, load: (value) => value === null ? null : new Date(value), }) } private _getColDefs(table: string, key: string) { const config = this.ctx.model.config[table] const { initial, nullable = initial === undefined || initial === null } = config.fields[key] let def = this.sql.escapeId(key) if (key === config.primary && config.autoInc) { def += ' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT' } else { const typedef = getTypeDefinition(config.fields[key]) def += ' ' + typedef + (nullable ? ' ' : ' NOT ') + 'NULL' if (initial !== undefined && initial !== null) { def += ' DEFAULT ' + this.sql.escape(this.caster.dump(table, { [key]: initial })[key]) } } return def } /** synchronize table schema */ private _syncTable(table: string) { const info = this.#exec('all', `PRAGMA table_info(${this.sql.escapeId(table)})`) as ISQLiteFieldInfo[] // FIXME: register platform columns before database initializion // WARN: side effecting Tables.config const config = this.ctx.model.config[table] if (table === 'user') { new Set(this.ctx.bots.map(bot => bot.platform)).forEach(platform => { config.fields[platform] = { type: 'string', length: 63 } config.unique.push(platform) }) } const keys = Object.keys(config.fields) if (info.length) { logger.info('auto updating table %c', table) const allKeys = [...keys, ...info.map(row => row.name)] for (const key of allKeys) { if (keys.includes(key) && info.some(({ name }) => name === key)) continue if (keys.includes(key)) { // Add column const def = this._getColDefs(table, key) this.#exec('run', `ALTER TABLE ${this.sql.escapeId(table)} ADD COLUMN ${def}`) } else { // Drop column this.#exec('run', `ALTER TABLE ${this.sql.escapeId(table)} DROP COLUMN ${this.sql.escapeId(key)}`) } } } else { logger.info('auto creating table %c', table) const defs = keys.map(key => this._getColDefs(table, key)) const constraints = [] if (config.primary && !config.autoInc) { constraints.push(`PRIMARY KEY (${this.#joinKeys(makeArray(config.primary))})`) } if (config.unique) { constraints.push(...config.unique.map(keys => `UNIQUE (${this.#joinKeys(makeArray(keys))})`)) } if (config.foreign) { constraints.push( ...Object.entries(config.foreign) .map(([key, [table, key2]]) => `FOREIGN KEY (${this.sql.escapeId(key)}) REFERENCES ${this.sql.escapeId(table)} (${this.sql.escapeId(key2)})`, ), ) } this.#exec('run', `CREATE TABLE ${this.sql.escapeId(table)} (${[...defs, ...constraints].join(',')})`) } } async start() { this.db = sqlite(this.config.path === ':memory:' ? this.config.path : resolve(this.config.path)) this.db.function('regexp', (pattern, str) => +new RegExp(pattern).test(str)) for (const name in this.ctx.model.config) { this._syncTable(name) } this.ctx.on('model', (name) => { this._syncTable(name) }) } #joinKeys(keys?: string[]) { return keys ? keys.map(key => this.sql.escapeId(key)).join(',') : '*' } stop() { this.db.close() } #exec<K extends 'get' | 'run' | 'all'>(action: K, sql: string, params: any = []) { try { const result = this.db.prepare(sql)[action](params) as ReturnType<Statement[K]> logger.debug('SQL > %c', sql) return result } catch (e) { logger.warn('SQL > %c', sql) throw e } } async drop() { const tables = Object.keys(this.ctx.model.config) for (const table of tables) { this.#exec('run', `DROP TABLE ${this.sql.escapeId(table)}`) } } async stats() { if (this.#path === ':memory:') return {} const { size } = await stat(this.#path) return { size } } async remove(name: TableType, query: Query) { const filter = this.#query(name, query) if (filter === '0') return this.#exec('run', `DELETE FROM ${this.sql.escapeId(name)} WHERE ${filter}`) } #query(name: TableType, query: Query) { return this.sql.parseQuery(this.ctx.model.resolveQuery(name, query)) } #get(name: TableType, query: Query, modifier: Query.Modifier) { const filter = this.#query(name, query) if (filter === '0') return [] const { fields, limit, offset, sort } = Query.resolveModifier(modifier) let sql = `SELECT ${this.#joinKeys(fields)} FROM ${this.sql.escapeId(name)} WHERE ${filter}` if (limit) sql += ' LIMIT ' + limit if (offset) sql += ' OFFSET ' + offset if (sort) sql += ' ORDER BY ' + Object.entries(sort).map(([key, order]) => `${this.sql.escapeId(key)} ${order}`).join(', ') const rows = this.#exec('all', sql) return rows.map(row => this.caster.load(name, row)) } async get(name: TableType, query: Query, modifier: Query.Modifier) { return this.#get(name, query, modifier) } #update(name: TableType, indexFields: string[], updateFields: string[], update: {}, data: {}) { const row = this.caster.dump(name, executeUpdate(data, update)) const assignment = updateFields.map((key) => `${this.sql.escapeId(key)} = ${this.sql.escape(row[key])}`).join(',') const query = Object.fromEntries(indexFields.map(key => [key, row[key]])) const filter = this.#query(name, query) this.#exec('run', `UPDATE ${this.sql.escapeId(name)} SET ${assignment} WHERE ${filter}`) } async set(name: TableType, query: Query, update: {}) { const { primary } = this.ctx.model.config[name] const updateFields = [...new Set(Object.keys(update).map(key => key.split('.', 1)[0]))] const indexFields = makeArray(primary) const fields = union(indexFields, updateFields) const table = this.#get(name, query, fields) for (const data of table) { this.#update(name, indexFields, updateFields, update, data) } } #create(name: TableType, data: {}) { data = this.caster.dump(name, data) const keys = Object.keys(data) const sql = `INSERT INTO ${this.sql.escapeId(name)} (${this.#joinKeys(keys)}) VALUES (${keys.map(key => this.sql.escape(data[key])).join(', ')})` return this.#exec('run', sql) } async create(name: TableType, data: {}) { data = { ...this.ctx.model.create(name), ...data } const result = this.#create(name, data) const { autoInc, primary } = this.ctx.model.config[name] if (!autoInc) return data as any return { ...data, [primary as string]: result.lastInsertRowid } } async upsert(name: TableType, updates: any[], keys: string | string[]) { if (!updates.length) return const { primary } = this.ctx.model.config[name] const merged = Object.assign({}, ...updates) const dataFields = [...new Set(Object.keys(merged).map(key => key.split('.', 1)[0]))] const indexFields = makeArray(keys || primary) const fields = union(indexFields, dataFields) const updateFields = difference(dataFields, indexFields) const table = this.#get(name, { $or: updates.map(item => Object.fromEntries(indexFields.map(key => [key, item[key]]))), }, fields) for (const item of updates) { let data = table.find(row => indexFields.every(key => row[key] === item[key])) if (data) { this.#update(name, indexFields, updateFields, item, data) } else { this.#create(name, executeUpdate(this.ctx.model.create(name), item)) } } } async eval(name: TableType, expr: any, query: Query) { const filter = this.#query(name, query) const output = this.sql.parseEval(expr) const { value } = this.#exec('get', `SELECT ${output} AS value FROM ${this.sql.escapeId(name)} WHERE ${filter}`) return value } } namespace SQLiteDatabase { export interface Config { path?: string } export const Config = Schema.object({ path: Schema.string().description('数据库路径').default('.koishi.db'), }) } export default SQLiteDatabase
the_stack
import { WordDocument } from './word-document'; import { DomType, IDomTable, IDomNumbering, IDomHyperlink, IDomImage, OpenXmlElement, IDomTableColumn, IDomTableCell, TextElement, SymbolElement, BreakElement } from './dom/dom'; import { Length, CommonProperties } from './dom/common'; import { Options } from './docx-preview'; import { DocumentElement } from './dom/document'; import { ParagraphElement } from './dom/paragraph'; import { appendClass, keyBy } from './utils'; import { updateTabStop } from './javascript'; import { FontTablePart } from './font-table/font-table'; import { SectionProperties } from './dom/section'; import { RunElement, RunProperties } from './dom/run'; import { BookmarkStartElement } from './dom/bookmark'; import { IDomStyle } from './dom/style'; import { NumberingPartProperties } from './numbering/numbering'; export class HtmlRenderer { inWrapper: boolean = true; className: string = "docx"; document: WordDocument; options: Options; constructor(public htmlDocument: HTMLDocument) { } render(document: WordDocument, bodyContainer: HTMLElement, styleContainer: HTMLElement = null, options: Options) { this.document = document; this.options = options; styleContainer = styleContainer || bodyContainer; removeAllElements(styleContainer); removeAllElements(bodyContainer); appendComment(styleContainer, "docxjs library predefined styles"); styleContainer.appendChild(this.renderDefaultStyle()); if (document.stylesPart != null) { appendComment(styleContainer, "docx document styles"); styleContainer.appendChild(this.renderStyles(document.stylesPart.styles)); } if (document.numberingPart) { appendComment(styleContainer, "docx document numbering styles"); styleContainer.appendChild(this.renderNumbering(document.numberingPart.domNumberings, styleContainer)); //styleContainer.appendChild(this.renderNumbering2(document.numberingPart, styleContainer)); } if(!options.ignoreFonts && document.fontTablePart) this.renderFontTable(document.fontTablePart, styleContainer); var sectionElements = this.renderSections(document.documentPart.body); if (this.inWrapper) { var wrapper = this.renderWrapper(); appentElements(wrapper, sectionElements); bodyContainer.appendChild(wrapper); } else { appentElements(bodyContainer, sectionElements); } } renderFontTable(fontsPart: FontTablePart, styleContainer: HTMLElement) { for(let f of fontsPart.fonts.filter(x => x.refId)) { this.document.loadFont(f.refId, f.fontKey).then(fontData => { var cssTest = `@font-face { font-family: "${f.name}"; src: url(${fontData}); }`; appendComment(styleContainer, `Font ${f.name}`); styleContainer.appendChild(createStyleElement(cssTest)); }); } } processClassName(className: string) { if (!className) return this.className; return `${this.className}_${className}`; } processStyles(styles: IDomStyle[]) { var stylesMap: Record<string, IDomStyle> = {}; for (let style of styles.filter(x => x.id != null)) { stylesMap[style.id] = style; } for (let style of styles.filter(x => x.basedOn)) { var baseStyle = stylesMap[style.basedOn]; if (baseStyle) { for (let styleValues of style.styles) { var baseValues = baseStyle.styles.filter(x => x.target == styleValues.target); if (baseValues && baseValues.length > 0) this.copyStyleProperties(baseValues[0].values, styleValues.values); } } else if (this.options.debug) console.warn(`Can't find base style ${style.basedOn}`); } for (let style of styles) { style.cssName = this.processClassName(this.escapeClassName(style.id)); } return stylesMap; } processElement(element: OpenXmlElement) { if (element.children) { for (var e of element.children) { e.className = this.processClassName(e.className); e.parent = element; if (e.type == DomType.Table) { this.processTable(e); } else { this.processElement(e); } } } } processTable(table: IDomTable) { for (var r of table.children) { for (var c of r.children) { c.cssStyle = this.copyStyleProperties(table.cellStyle, c.cssStyle, [ "border-left", "border-right", "border-top", "border-bottom", "padding-left", "padding-right", "padding-top", "padding-bottom" ]); this.processElement(c); } } } copyStyleProperties(input: Record<string, string>, output: Record<string, string>, attrs: string[] = null): Record<string, string> { if (!input) return output; if (output == null) output = {}; if (attrs == null) attrs = Object.getOwnPropertyNames(input); for (var key of attrs) { if (input.hasOwnProperty(key) && !output.hasOwnProperty(key)) output[key] = input[key]; } return output; } createSection(className: string, props: SectionProperties) { var elem = this.htmlDocument.createElement("section"); elem.className = className; if (props) { if (props.pageMargins) { elem.style.paddingLeft = this.renderLength(props.pageMargins.left); elem.style.paddingRight = this.renderLength(props.pageMargins.right); elem.style.paddingTop = this.renderLength(props.pageMargins.top); elem.style.paddingBottom = this.renderLength(props.pageMargins.bottom); } if (props.pageSize) { if (!this.options.ignoreWidth) elem.style.width = this.renderLength(props.pageSize.width); if (!this.options.ignoreHeight) elem.style.minHeight = this.renderLength(props.pageSize.height); } if (props.columns && props.columns.numberOfColumns) { elem.style.columnCount = `${props.columns.numberOfColumns}`; elem.style.columnGap = this.renderLength(props.columns.space); if (props.columns.separator) { elem.style.columnRule = "1px solid black"; } } } return elem; } renderSections(document: DocumentElement): HTMLElement[] { var result = []; this.processElement(document); for(let section of this.splitBySection(document.children)) { var sectionElement = this.createSection(this.className, section.sectProps || document.props); this.renderElements(section.elements, document, sectionElement); result.push(sectionElement); } return result; } splitBySection(elements: OpenXmlElement[]): { sectProps: SectionProperties, elements: OpenXmlElement[] }[] { var current = { sectProps: null, elements: [] }; var result = [current]; var styles = this.document.stylesPart?.styles; var styleMap = styles ? keyBy(styles, x => x.id) : null; for(let elem of elements) { if(elem.type == DomType.Paragraph) { const styleName = (elem as ParagraphElement).styleName; const s = styleMap && styleName ? styleMap[styleName] : null; if(s?.paragraphProps?.pageBreakBefore) { current.sectProps = sectProps; current = { sectProps: null, elements: [] }; result.push(current); } } current.elements.push(elem); if(elem.type == DomType.Paragraph) { const p = elem as ParagraphElement; var sectProps = p.sectionProps; var pBreakIndex = -1; var rBreakIndex = -1; if(this.options.breakPages && p.children) { pBreakIndex = p.children.findIndex(r => { rBreakIndex = r.children?.findIndex(t => (t as BreakElement).break == "page") ?? -1; return rBreakIndex != -1; }); } if(sectProps || pBreakIndex != -1) { current.sectProps = sectProps; current = { sectProps: null, elements: [] }; result.push(current); } if(pBreakIndex != -1) { let breakRun = p.children[pBreakIndex]; let splitRun = rBreakIndex < breakRun.children.length - 1; if(pBreakIndex < p.children.length - 1 || splitRun) { var children = elem.children; var newParagraph = { ...elem, children: children.slice(pBreakIndex) }; elem.children = children.slice(0, pBreakIndex); current.elements.push(newParagraph); if(splitRun) { let runChildren = breakRun.children; let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) }; elem.children.push(newRun); breakRun.children = runChildren.slice(rBreakIndex); } } } } } let currentSectProps = null; for (let i = result.length - 1; i >= 0; i--) { if (result[i].sectProps == null) { result[i].sectProps = currentSectProps; } else { currentSectProps = result[i].sectProps } } return result; } renderLength(l: Length): string { return l ? `${l.value}${l.type}` : null; } renderWrapper() { var wrapper = document.createElement("div"); wrapper.className = `${this.className}-wrapper` return wrapper; } renderDefaultStyle() { var styleText = `.${this.className}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } .${this.className}-wrapper section.${this.className} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; } .${this.className} { color: black; } section.${this.className} { box-sizing: border-box; } .${this.className} table { border-collapse: collapse; } .${this.className} table td, .${this.className} table th { vertical-align: top; } .${this.className} p { margin: 0pt; }`; return createStyleElement(styleText); } // renderNumbering2(numberingPart: NumberingPartProperties, container: HTMLElement): HTMLElement { // let css = ""; // const numberingMap = keyBy(numberingPart.abstractNumberings, x => x.id); // const bulletMap = keyBy(numberingPart.bulletPictures, x => x.id); // const topCounters = []; // for(let num of numberingPart.numberings) { // const absNum = numberingMap[num.abstractId]; // for(let lvl of absNum.levels) { // const className = this.numberingClass(num.id, lvl.level); // let listStyleType = "none"; // if(lvl.text && lvl.format == 'decimal') { // const counter = this.numberingCounter(num.id, lvl.level); // if (lvl.level > 0) { // css += this.styleToString(`p.${this.numberingClass(num.id, lvl.level - 1)}`, { // "counter-reset": counter // }); // } else { // topCounters.push(counter); // } // css += this.styleToString(`p.${className}:before`, { // "content": this.levelTextToContent(lvl.text, num.id), // "counter-increment": counter // }); // } else if(lvl.bulletPictureId) { // let pict = bulletMap[lvl.bulletPictureId]; // let variable = `--${this.className}-${pict.referenceId}`.toLowerCase(); // css += this.styleToString(`p.${className}:before`, { // "content": "' '", // "display": "inline-block", // "background": `var(${variable})` // }, pict.style); // this.document.loadNumberingImage(pict.referenceId).then(data => { // var text = `.${this.className}-wrapper { ${variable}: url(${data}) }`; // container.appendChild(createStyleElement(text)); // }); // } else { // listStyleType = this.numFormatToCssValue(lvl.format); // } // css += this.styleToString(`p.${className}`, { // "display": "list-item", // "list-style-position": "inside", // "list-style-type": listStyleType, // //TODO // //...num.style // }); // } // } // if (topCounters.length > 0) { // css += this.styleToString(`.${this.className}-wrapper`, { // "counter-reset": topCounters.join(" ") // }); // } // return createStyleElement(css); // } renderNumbering(styles: IDomNumbering[], styleContainer: HTMLElement) { var styleText = ""; var rootCounters = []; for (var num of styles) { var selector = `p.${this.numberingClass(num.id, num.level)}`; var listStyleType = "none"; if (num.levelText && num.format == "decimal") { let counter = this.numberingCounter(num.id, num.level); if (num.level > 0) { styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, { "counter-reset": counter }); } else { rootCounters.push(counter); } styleText += this.styleToString(`${selector}:before`, { "content": this.levelTextToContent(num.levelText, num.id), "counter-increment": counter }); } else if (num.bullet) { let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase(); styleText += this.styleToString(`${selector}:before`, { "content": "' '", "display": "inline-block", "background": `var(${valiable})` }, num.bullet.style); this.document.loadNumberingImage(num.bullet.src).then(data => { var text = `.${this.className}-wrapper { ${valiable}: url(${data}) }`; styleContainer.appendChild(createStyleElement(text)); }); } else { listStyleType = this.numFormatToCssValue(num.format); } styleText += this.styleToString(selector, { "display": "list-item", "list-style-position": "inside", "list-style-type": listStyleType, ...num.style }); } if (rootCounters.length > 0) { styleText += this.styleToString(`.${this.className}-wrapper`, { "counter-reset": rootCounters.join(" ") }); } return createStyleElement(styleText); } renderStyles(styles: IDomStyle[]): HTMLElement { var styleText = ""; var stylesMap = this.processStyles(styles); for (let style of styles) { var subStyles = style.styles; if(style.linked) { var linkedStyle = style.linked && stylesMap[style.linked]; if (linkedStyle) subStyles = subStyles.concat(linkedStyle.styles); else if(this.options.debug) console.warn(`Can't find linked style ${style.linked}`); } for (var subStyle of subStyles) { var selector = ""; if (style.target == subStyle.target) selector += `${style.target}.${style.cssName}`; else if (style.target) selector += `${style.target}.${style.cssName} ${subStyle.target}`; else selector += `.${style.cssName} ${subStyle.target}`; if (style.isDefault && style.target) selector = `.${this.className} ${style.target}, ` + selector; styleText += this.styleToString(selector, subStyle.values); } } return createStyleElement(styleText); } renderElement(elem: OpenXmlElement, parent: OpenXmlElement): Node { switch (elem.type) { case DomType.Paragraph: return this.renderParagraph(<ParagraphElement>elem); case DomType.BookmarkStart: return this.renderBookmarkStart(<BookmarkStartElement>elem); case DomType.BookmarkEnd: return null; case DomType.Run: return this.renderRun(<RunElement>elem); case DomType.Table: return this.renderTable(elem); case DomType.Row: return this.renderTableRow(elem); case DomType.Cell: return this.renderTableCell(elem); case DomType.Hyperlink: return this.renderHyperlink(elem); case DomType.Drawing: return this.renderDrawing(<IDomImage>elem); case DomType.Image: return this.renderImage(<IDomImage>elem); case DomType.Text: return this.renderText(<TextElement>elem); case DomType.Tab: return this.renderTab(elem); case DomType.Symbol: return this.renderSymbol(<SymbolElement>elem); } return null; } renderChildren(elem: OpenXmlElement, into?: HTMLElement): Node[] { return this.renderElements(elem.children, elem, into); } renderElements(elems: OpenXmlElement[], parent: OpenXmlElement, into?: HTMLElement): Node[] { if(elems == null) return null; var result = elems.map(e => this.renderElement(e, parent)).filter(e => e != null); if(into) for(let c of result) into.appendChild(c); return result; } renderParagraph(elem: ParagraphElement) { var result = this.htmlDocument.createElement("p"); this.renderClass(elem, result); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); this.renderCommonProeprties(result.style, elem); if (elem.numbering) { var numberingClass = this.numberingClass(elem.numbering.id, elem.numbering.level); result.className = appendClass(result.className, numberingClass); } if (elem.styleName) { var styleClassName = this.processClassName(this.escapeClassName(elem.styleName)); result.className = appendClass(result.className, styleClassName); } return result; } renderRunProperties(style: any, props: RunProperties) { this.renderCommonProeprties(style, props); } renderCommonProeprties(style: any, props: CommonProperties){ if(props == null) return; if(props.color) { style["color"] = props.color; } if (props.fontSize) { style["font-size"] = this.renderLength(props.fontSize); } } renderHyperlink(elem: IDomHyperlink) { var result = this.htmlDocument.createElement("a"); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); if (elem.href) result.href = elem.href return result; } renderDrawing(elem: IDomImage) { var result = this.htmlDocument.createElement("div"); result.style.display = "inline-block"; result.style.position = "relative"; result.style.textIndent = "0px"; this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); return result; } renderImage(elem: IDomImage) { let result = this.htmlDocument.createElement("img"); this.renderStyleValues(elem.cssStyle, result); if (this.document) { this.document.loadDocumentImage(elem.src).then(x => { result.src = x; }); } return result; } renderText(elem: TextElement) { return this.htmlDocument.createTextNode(elem.text); } renderSymbol(elem: SymbolElement) { var span = this.htmlDocument.createElement("span"); span.style.fontFamily = elem.font; span.innerHTML = `&#x${elem.char};` return span; } renderTab(elem: OpenXmlElement) { var tabSpan = this.htmlDocument.createElement("span"); tabSpan.innerHTML = "&emsp;";//"&nbsp;"; if(this.options.experimental) { setTimeout(() => { var paragraph = findParent<ParagraphElement>(elem, DomType.Paragraph); if(paragraph.tabs == null) return; paragraph.tabs.sort((a, b) => a.position.value - b.position.value); tabSpan.style.display = "inline-block"; updateTabStop(tabSpan, paragraph.tabs); }, 0); } return tabSpan; } renderBookmarkStart(elem: BookmarkStartElement): HTMLElement { var result = this.htmlDocument.createElement("span"); result.id = elem.name; return result; } renderRun(elem: RunElement) { if (elem.break) return elem.break == "page" ? null : this.htmlDocument.createElement("br"); if (elem.fldCharType || elem.instrText) return null; var result = this.htmlDocument.createElement("span"); if(elem.id) result.id = elem.id; this.renderClass(elem, result); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); if (elem.href) { var link = this.htmlDocument.createElement("a"); link.href = elem.href; link.appendChild(result); return link; } else if (elem.wrapper) { var wrapper = this.htmlDocument.createElement(elem.wrapper); wrapper.appendChild(result); return wrapper; } return result; } renderTable(elem: IDomTable) { let result = this.htmlDocument.createElement("table"); if (elem.columns) result.appendChild(this.renderTableColumns(elem.columns)); this.renderClass(elem, result); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); return result; } renderTableColumns(columns: IDomTableColumn[]) { let result = this.htmlDocument.createElement("colGroup"); for (let col of columns) { let colElem = this.htmlDocument.createElement("col"); if (col.width) colElem.style.width = `${col.width}px`; result.appendChild(colElem); } return result; } renderTableRow(elem: OpenXmlElement) { let result = this.htmlDocument.createElement("tr"); this.renderClass(elem, result); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); return result; } renderTableCell(elem: IDomTableCell) { let result = this.htmlDocument.createElement("td"); this.renderClass(elem, result); this.renderChildren(elem, result); this.renderStyleValues(elem.cssStyle, result); if (elem.span) result.colSpan = elem.span; return result; } renderStyleValues(style: Record<string, string>, ouput: HTMLElement) { if (style == null) return; for (let key in style) { if (style.hasOwnProperty(key)) { ouput.style[key] = style[key]; } } } renderClass(input: OpenXmlElement, ouput: HTMLElement) { if (input.className) ouput.className = input.className; } numberingClass(id: string, lvl: number) { return `${this.className}-num-${id}-${lvl}`; } styleToString(selectors: string, values: Record<string, string>, cssText: string = null) { let result = selectors + " {\r\n"; for (const key in values) { result += ` ${key}: ${values[key]};\r\n`; } if (cssText) result += ";" + cssText; return result + "}\r\n"; } numberingCounter(id: string, lvl: number) { return `${this.className}-num-${id}-${lvl}`; } levelTextToContent(text: string, id: string) { var result = text.replace(/%\d*/g, s => { let lvl = parseInt(s.substring(1), 10) - 1; return `"counter(${this.numberingCounter(id, lvl)})"`; }); return '"' + result + '"'; } numFormatToCssValue(format: string) { var mapping = { "none": "none", "bullet": "disc", "decimal": "decimal", "lowerLetter": "lower-alpha", "upperLetter": "upper-alpha", "lowerRoman": "lower-roman", "upperRoman": "upper-roman", }; return mapping[format] || format; } escapeClassName(className: string) { return className?.replace(/[ .]+/g, '-').replace(/[&]+/g, 'and'); } } function appentElements(container: HTMLElement, children: HTMLElement[]) { for (let c of children) container.appendChild(c); } function removeAllElements(elem: HTMLElement) { while (elem.firstChild) { elem.removeChild(elem.firstChild); } } function createStyleElement(cssText: string) { var styleElement = document.createElement("style"); styleElement.innerHTML = cssText; return styleElement; } function appendComment(elem: HTMLElement, comment: string) { elem.appendChild(document.createComment(comment)); } function findParent<T extends OpenXmlElement>(elem: OpenXmlElement, type: DomType): T { var parent = elem.parent; while (parent != null && parent.type != type) parent = parent.parent; return <T>parent; }
the_stack
import {AnyAction, PayloadAction, createSelector, createSlice} from '@reduxjs/toolkit' import type {ClientError, Patch, Transaction} from '@sanity/client' import { Asset, AssetItem, AssetType, BrowserView, HttpError, Order, OrderDirection, Tag } from '@types' import groq from 'groq' import {nanoid} from 'nanoid' import {Epic, ofType} from 'redux-observable' import {Selector} from 'react-redux' import {empty, from, of} from 'rxjs' import { bufferTime, catchError, debounceTime, filter, mergeMap, switchMap, withLatestFrom } from 'rxjs/operators' import {client} from '../../client' import {getOrderTitle} from '../../config/orders' import {ORDER_OPTIONS} from '../../constants' import constructFilter from '../../utils/constructFilter' import debugThrottle from '../../operators/debugThrottle' import {RootReducerState} from '../types' import {searchActions} from '../search' import {uploadsActions} from '../uploads' type ItemError = { description: string id: string referencingIDs: string[] type: string // 'documentHasExistingReferencesError' } export type AssetsReducerState = { allIds: string[] assetTypes: AssetType[] byIds: Record<string, AssetItem> fetchCount: number fetching: boolean fetchingError?: HttpError lastPicked?: string order: Order pageIndex: number pageSize: number view: BrowserView // totalCount: number } const defaultOrder = ORDER_OPTIONS[0] as { direction: OrderDirection field: string } /** * NOTE: * `fetchCount` returns the number of items retrieved in the most recent fetch. * This is a temporary workaround to be able to determine when there are no more items to retrieve. * Typically this would be done by deriving the total number of assets upfront, but currently such * queries in GROQ aren't fast enough to use on large datasets (1000s of entries). * * TODO: * When the query engine has been improved and above queries are faster, remove all instances of * of `fetchCount` and reinstate `totalCount` across the board. */ export const initialState = { allIds: [], assetTypes: [], byIds: {}, fetchCount: -1, fetching: false, fetchingError: undefined, lastPicked: undefined, order: { direction: defaultOrder.direction, field: defaultOrder.field, title: getOrderTitle(defaultOrder.field, defaultOrder.direction) }, pageIndex: 0, pageSize: 50, // totalCount: -1, view: 'grid' } as AssetsReducerState const assetsSlice = createSlice({ name: 'assets', initialState, extraReducers: builder => { builder // .addCase(uploadsActions.uploadComplete, (state, action) => { const {asset} = action.payload state.byIds[asset._id] = { _type: 'asset', asset: asset as Asset, picked: false, updating: false } }) }, reducers: { // Clear asset order clear(state) { state.allIds = [] }, // Remove assets and update page index deleteComplete(state, action: PayloadAction<{assetIds: string[]}>) { const {assetIds} = action.payload assetIds?.forEach(id => { const deleteIndex = state.allIds.indexOf(id) if (deleteIndex >= 0) { state.allIds.splice(deleteIndex, 1) } delete state.byIds[id] }) state.pageIndex = Math.floor(state.allIds.length / state.pageSize) - 1 }, deleteError(state, action: PayloadAction<{assetIds: string[]; error: ClientError}>) { const {assetIds, error} = action.payload const itemErrors: ItemError[] = error?.response?.body?.error?.items?.map( (item: any) => item.error ) assetIds?.forEach(id => { state.byIds[id].updating = false }) itemErrors?.forEach(item => { state.byIds[item.id].error = item.description }) }, deleteRequest(state, action: PayloadAction<{assets: Asset[]; closeDialogId?: string}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset?._id].updating = true }) Object.keys(state.byIds).forEach(key => { delete state.byIds[key].error }) }, fetchComplete(state, action: PayloadAction<{assets: Asset[]}>) { const assets = action.payload?.assets || [] if (assets) { assets.forEach(asset => { if (!state.allIds.includes(asset._id)) { state.allIds.push(asset._id) } state.byIds[asset._id] = { _type: 'asset', asset: asset, picked: false, updating: false } }) } state.fetching = false state.fetchCount = assets.length || 0 delete state.fetchingError }, fetchError(state, action: PayloadAction<HttpError>) { const error = action.payload state.fetching = false state.fetchingError = error }, fetchRequest: { reducer: (state, _action: PayloadAction<{params: Record<string, any>; query: string}>) => { state.fetching = true delete state.fetchingError }, prepare: ({ filter, params = {}, selector = ``, sort = groq`order(_updatedAt desc)` }: { filter: string params?: Record<string, any> replace?: boolean selector?: string sort?: string }) => { const pipe = sort || selector ? '|' : '' // Construct query const query = groq` { "items": *[${filter}] { _id, _type, _createdAt, _updatedAt, altText, description, extension, metadata { dimensions, exif, isOpaque, }, mimeType, opt { media }, originalFilename, size, title, url } ${pipe} ${sort} ${selector}, } ` return {payload: {params, query}} } }, insertUploads(state, action: PayloadAction<{results: Record<string, string | null>}>) { const {results} = action.payload Object.entries(results).forEach(([hash, assetId]) => { if (assetId && !state.allIds.includes(hash)) { state.allIds.push(assetId) } }) }, listenerCreateQueue(_state, _action: PayloadAction<{asset: Asset}>) { // }, listenerCreateQueueComplete(state, action: PayloadAction<{assets: Asset[]}>) { const {assets} = action.payload assets?.forEach(asset => { if (state.byIds[asset?._id]?.asset) { state.byIds[asset._id].asset = asset } }) }, listenerDeleteQueue(_state, _action: PayloadAction<{assetId: string}>) { // }, listenerDeleteQueueComplete(state, action: PayloadAction<{assetIds: string[]}>) { const {assetIds} = action.payload assetIds?.forEach(assetId => { const deleteIndex = state.allIds.indexOf(assetId) if (deleteIndex >= 0) { state.allIds.splice(deleteIndex, 1) } delete state.byIds[assetId] }) }, listenerUpdateQueue(_state, _action: PayloadAction<{asset: Asset}>) { // }, listenerUpdateQueueComplete(state, action: PayloadAction<{assets: Asset[]}>) { const {assets} = action.payload assets?.forEach(asset => { if (state.byIds[asset?._id]?.asset) { state.byIds[asset._id].asset = asset } }) }, loadNextPage() { // }, loadPageIndex(state, action: PayloadAction<{pageIndex: number}>) { // state.pageIndex = action.payload.pageIndex }, orderSet(state, action: PayloadAction<{order: Order}>) { state.order = action.payload?.order state.pageIndex = 0 }, pick(state, action: PayloadAction<{assetId: string; picked: boolean}>) { const {assetId, picked} = action.payload state.byIds[assetId].picked = picked state.lastPicked = picked ? assetId : undefined }, pickAll(state) { state.allIds.forEach(id => { state.byIds[id].picked = true }) }, pickClear(state) { state.lastPicked = undefined Object.values(state.byIds).forEach(asset => { state.byIds[asset.asset._id].picked = false }) }, pickRange(state, action: PayloadAction<{endId: string; startId: string}>) { const startIndex = state.allIds.findIndex(id => id === action.payload.startId) const endIndex = state.allIds.findIndex(id => id === action.payload.endId) // Sort numerically, ascending order const indices = [startIndex, endIndex].sort((a, b) => a - b) state.allIds.slice(indices[0], indices[1] + 1).forEach(key => { state.byIds[key].picked = true }) state.lastPicked = state.allIds[endIndex] }, sort(state) { state.allIds.sort((a, b) => { const tagA = state.byIds[a].asset[state.order.field] const tagB = state.byIds[b].asset[state.order.field] if (tagA < tagB) { return state.order.direction === 'asc' ? -1 : 1 } else if (tagA > tagB) { return state.order.direction === 'asc' ? 1 : -1 } else { return 0 } }) }, tagsAddComplete(state, action: PayloadAction<{assets: AssetItem[]; tag: Tag}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = false }) }, tagsAddError(state, action: PayloadAction<{assets: AssetItem[]; error: HttpError; tag: Tag}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = false }) }, tagsAddRequest(state, action: PayloadAction<{assets: AssetItem[]; tag: Tag}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = true }) }, tagsRemoveComplete(state, action: PayloadAction<{assets: AssetItem[]; tag: Tag}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = false }) }, tagsRemoveError( state, action: PayloadAction<{assets: AssetItem[]; error: HttpError; tag: Tag}> ) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = false }) }, tagsRemoveRequest(state, action: PayloadAction<{assets: AssetItem[]; tag: Tag}>) { const {assets} = action.payload assets.forEach(asset => { state.byIds[asset.asset._id].updating = true }) }, updateComplete(state, action: PayloadAction<{asset: Asset; closeDialogId?: string}>) { const {asset} = action.payload state.byIds[asset._id].updating = false state.byIds[asset._id].asset = asset }, updateError(state, action: PayloadAction<{asset: Asset; error: HttpError}>) { const {asset, error} = action.payload const assetId = asset?._id state.byIds[assetId].error = error.message state.byIds[assetId].updating = false }, updateRequest( state, action: PayloadAction<{asset: Asset; closeDialogId?: string; formData: Record<string, any>}> ) { const assetId = action.payload?.asset?._id state.byIds[assetId].updating = true }, viewSet(state, action: PayloadAction<{view: BrowserView}>) { state.view = action.payload?.view } } }) // Epics type MyEpic = Epic<AnyAction, AnyAction, RootReducerState> export const assetsDeleteEpic: MyEpic = action$ => action$.pipe( filter(assetsActions.deleteRequest.match), mergeMap(action => { const {assets} = action.payload const assetIds = assets.map(asset => asset._id) return of(assets).pipe( mergeMap(() => client.observable.delete({ query: groq`*[_id in ${JSON.stringify(assetIds)}]` }) ), mergeMap(() => of(assetsActions.deleteComplete({assetIds}))), catchError((error: ClientError) => { return of(assetsActions.deleteError({assetIds, error})) }) ) }) ) export const assetsFetchEpic: MyEpic = (action$, state$) => action$.pipe( filter(assetsActions.fetchRequest.match), withLatestFrom(state$), switchMap(([action, state]) => { const params = action.payload?.params const query = action.payload?.query return of(action).pipe( debugThrottle(state.debug.badConnection), mergeMap(() => client.observable.fetch<{ items: Asset[] }>(query, params) ), mergeMap(result => { const { items // totalCount } = result return of(assetsActions.fetchComplete({assets: items})) }), catchError((error: ClientError) => of( assetsActions.fetchError({ message: error?.message || 'Internal error', statusCode: error?.statusCode || 500 }) ) ) ) }) ) export const assetsFetchPageIndexEpic: MyEpic = (action$, state$) => action$.pipe( filter(assetsActions.loadPageIndex.match), withLatestFrom(state$), switchMap(([action, state]) => { const pageSize = state.assets.pageSize const start = action.payload.pageIndex * pageSize const end = start + pageSize // Document ID can be null when operating on pristine / unsaved drafts const documentId = state?.selected.document?._id const documentAssetIds = state?.selected?.documentAssetIds const filter = constructFilter({ assetTypes: state.assets.assetTypes, searchFacets: state.search.facets, searchQuery: state.search.query }) const params = { ...(documentId ? {documentId} : {}), documentAssetIds } return of( assetsActions.fetchRequest({ filter, params, selector: groq`[${start}...${end}]`, sort: groq`order(${state.assets?.order?.field} ${state.assets?.order?.direction})` }) ) }) ) export const assetsFetchNextPageEpic: MyEpic = (action$, state$) => action$.pipe( filter(assetsActions.loadNextPage.match), withLatestFrom(state$), switchMap(([_, state]) => of(assetsActions.loadPageIndex({pageIndex: state.assets.pageIndex + 1})) ) ) export const assetsFetchAfterDeleteAllEpic: MyEpic = (action$, state$) => action$.pipe( filter(assetsActions.deleteComplete.match), withLatestFrom(state$), switchMap(([_, state]) => { if (state.assets.allIds.length === 0) { const nextPageIndex = Math.floor(state.assets.allIds.length / state.assets.pageSize) return of(assetsActions.loadPageIndex({pageIndex: nextPageIndex})) } return empty() }) ) export const assetsRemoveTagsEpic: MyEpic = (action$, state$) => { return action$.pipe( filter(assetsActions.tagsAddRequest.match), withLatestFrom(state$), mergeMap(([action, state]) => { const {assets, tag} = action.payload return of(action).pipe( // Optionally throttle debugThrottle(state.debug.badConnection), // Add tag references to all picked assets mergeMap(() => { const pickedAssets = selectAssetsPicked(state) // Filter out picked assets which already include tag const pickedAssetsFiltered = pickedAssets?.filter(assetItem => { const tagIndex = assetItem?.asset?.opt?.media?.tags?.findIndex(t => t._ref === tag?._id) ?? -1 return tagIndex < 0 }) const transaction: Transaction = pickedAssetsFiltered.reduce( (transaction, pickedAsset) => { return transaction.patch(pickedAsset?.asset?._id, (patch: Patch) => patch .setIfMissing({opt: {}}) .setIfMissing({'opt.media': {}}) .setIfMissing({'opt.media.tags': []}) .append('opt.media.tags', [ {_key: nanoid(), _ref: tag?._id, _type: 'reference', _weak: true} ]) ) }, client.transaction() ) return from(transaction.commit()) }), // Dispatch complete action mergeMap(() => of(assetsActions.tagsAddComplete({assets, tag}))), catchError((error: ClientError) => of( assetsActions.tagsAddError({ assets, error: { message: error?.message || 'Internal error', statusCode: error?.statusCode || 500 }, tag }) ) ) ) }) ) } export const assetsOrderSetEpic: MyEpic = action$ => action$.pipe( filter(assetsActions.orderSet.match), mergeMap(() => { return of( assetsActions.clear(), // assetsActions.loadPageIndex({pageIndex: 0}) ) }) ) export const assetsSearchEpic: MyEpic = action$ => action$.pipe( ofType( searchActions.facetsAdd.type, searchActions.facetsClear.type, searchActions.facetsRemove.type, searchActions.facetsUpdate.type, searchActions.querySet.type ), debounceTime(400), mergeMap(() => { return of( assetsActions.clear(), // assetsActions.loadPageIndex({pageIndex: 0}) ) }) ) export const assetsListenerCreateQueueEpic: MyEpic = action$ => action$.pipe( filter(assetsActions.listenerCreateQueue.match), bufferTime(2000), filter(actions => actions.length > 0), mergeMap(actions => { const assets = actions?.map(action => action.payload.asset) return of(assetsActions.listenerCreateQueueComplete({assets})) }) ) export const assetsListenerDeleteQueueEpic: MyEpic = action$ => action$.pipe( filter(assetsActions.listenerDeleteQueue.match), bufferTime(2000), filter(actions => actions.length > 0), mergeMap(actions => { const assetIds = actions?.map(action => action.payload.assetId) return of(assetsActions.listenerDeleteQueueComplete({assetIds})) }) ) export const assetsListenerUpdateQueueEpic: MyEpic = action$ => action$.pipe( filter(assetsActions.listenerUpdateQueue.match), bufferTime(2000), filter(actions => actions.length > 0), mergeMap(actions => { const assets = actions?.map(action => action.payload.asset) return of(assetsActions.listenerUpdateQueueComplete({assets})) }) ) // Re-sort on all updates (immediate and batched listener events) export const assetsSortEpic: MyEpic = action$ => action$.pipe( ofType( assetsActions.insertUploads.type, assetsActions.listenerUpdateQueueComplete.type, assetsActions.updateComplete.type ), mergeMap(() => of(assetsActions.sort())) ) export const assetsTagsAddEpic: MyEpic = (action$, state$) => { return action$.pipe( filter(assetsActions.tagsAddRequest.match), withLatestFrom(state$), mergeMap(([action, state]) => { const {assets, tag} = action.payload return of(action).pipe( // Optionally throttle debugThrottle(state.debug.badConnection), // Add tag references to all picked assets mergeMap(() => { const pickedAssets = selectAssetsPicked(state) // Filter out picked assets which already include tag const pickedAssetsFiltered = pickedAssets?.filter(assetItem => { const tagIndex = assetItem?.asset?.opt?.media?.tags?.findIndex(t => t._ref === tag?._id) ?? -1 return tagIndex < 0 }) const transaction: Transaction = pickedAssetsFiltered.reduce( (transaction, pickedAsset) => { return transaction.patch(pickedAsset?.asset?._id, (patch: Patch) => patch .ifRevisionId(pickedAsset?.asset?._rev) .setIfMissing({opt: {}}) .setIfMissing({'opt.media': {}}) .setIfMissing({'opt.media.tags': []}) .append('opt.media.tags', [ {_key: nanoid(), _ref: tag?._id, _type: 'reference', _weak: true} ]) ) }, client.transaction() ) return from(transaction.commit()) }), // Dispatch complete action mergeMap(() => of(assetsActions.tagsAddComplete({assets, tag}))), catchError((error: ClientError) => of( assetsActions.tagsAddError({ assets, error: { message: error?.message || 'Internal error', statusCode: error?.statusCode || 500 }, tag }) ) ) ) }) ) } export const assetsTagsRemoveEpic: MyEpic = (action$, state$) => { return action$.pipe( filter(assetsActions.tagsRemoveRequest.match), withLatestFrom(state$), mergeMap(([action, state]) => { const {assets, tag} = action.payload return of(action).pipe( // Optionally throttle debugThrottle(state.debug.badConnection), // Remove tag references from all picked assets mergeMap(() => { const pickedAssets = selectAssetsPicked(state) const transaction: Transaction = pickedAssets.reduce((transaction, pickedAsset) => { return transaction.patch(pickedAsset?.asset?._id, (patch: Patch) => patch .ifRevisionId(pickedAsset?.asset?._rev) .unset([`opt.media.tags[_ref == "${tag._id}"]`]) ) }, client.transaction()) return from(transaction.commit()) }), // Dispatch complete action mergeMap(() => of(assetsActions.tagsRemoveComplete({assets, tag}))), catchError((error: ClientError) => of( assetsActions.tagsRemoveError({ assets, error: { message: error?.message || 'Internal error', statusCode: error?.statusCode || 500 }, tag }) ) ) ) }) ) } export const assetsUnpickEpic: MyEpic = action$ => action$.pipe( ofType( assetsActions.orderSet.type, assetsActions.viewSet.type, searchActions.facetsAdd.type, searchActions.facetsClear.type, searchActions.facetsRemove.type, searchActions.facetsUpdate.type, searchActions.querySet.type ), mergeMap(() => { return of(assetsActions.pickClear()) }) ) export const assetsUpdateEpic: MyEpic = (action$, state$) => action$.pipe( filter(assetsActions.updateRequest.match), withLatestFrom(state$), mergeMap(([action, state]) => { const {asset, closeDialogId, formData} = action.payload return of(action).pipe( debugThrottle(state.debug.badConnection), mergeMap(() => from( client .patch(asset._id) .setIfMissing({opt: {}}) .setIfMissing({'opt.media': {}}) .set(formData) .commit() ) ), mergeMap((updatedAsset: any) => of( assetsActions.updateComplete({ asset: updatedAsset, closeDialogId }) ) ), catchError((error: ClientError) => of( assetsActions.updateError({ asset, error: { message: error?.message || 'Internal error', statusCode: error?.statusCode || 500 } }) ) ) ) }) ) // Selectors const selectAssetsByIds = (state: RootReducerState) => state.assets.byIds const selectAssetsAllIds = (state: RootReducerState) => state.assets.allIds export const selectAssetById = createSelector( [ (state: RootReducerState) => state.assets.byIds, (_state: RootReducerState, assetId: string) => assetId ], (byIds, assetId) => byIds[assetId] ) export const selectAssets: Selector<RootReducerState, AssetItem[]> = createSelector( [selectAssetsByIds, selectAssetsAllIds], (byIds, allIds) => allIds.map(id => byIds[id]) ) export const selectAssetsLength = createSelector([selectAssets], assets => assets.length) export const selectAssetsPicked = createSelector([selectAssets], assets => assets.filter(item => item?.picked) ) export const selectAssetsPickedLength = createSelector( [selectAssetsPicked], assetsPicked => assetsPicked.length ) export const assetsActions = assetsSlice.actions export default assetsSlice.reducer
the_stack
import { hashPersonalMessage, ecrecover } from 'ethereumjs-util'; import Common from 'ethereumjs-common'; import { safeIntegerValidator, bigNumberValidator, addressValidator, hexSequenceValidator, messageValidator, messageDataValidator, } from './validators'; import { hexSequenceNormalizer, recoveryParamNormalizer } from './normalizers'; import { bigNumber, warning } from './utils'; import { helpers as helperMessages } from './messages'; import { CHAIN_IDS, HARDFORKS, HEX_HASH_TYPE, NETWORK_NAMES, PATH, TRANSACTION, } from './constants'; import { DerivationPathObjectType, VerifyMessageData, TransactionObjectTypeWithTo, TransactionOptions, } from './types'; /** * Serialize an derivation path object's props into it's string counterpart * * @method derivationPathSerializer * * @param {number} purpose path purpose * @param {number} coinType path coin type (and network) * @param {number} account path account number * @param {number} change path change number * @param {number} addressIndex address index (no default since it should be manually added) * * See the defaults file for some more information regarding the format of the * Ethereum deviation path. * * All the above params are sent in as props of an {DerivationPathObjectType} object. * * @return {string} The serialized path */ export const derivationPathSerializer = ({ purpose = PATH.PURPOSE, coinType = PATH.COIN_MAINNET, account = PATH.ACCOUNT, change, addressIndex, }: DerivationPathObjectType = {}): string => { const { DELIMITER } = PATH; const hasChange = change || change === 0; const hasAddressIndex = addressIndex || addressIndex === 0; return `${ `${PATH.HEADER_KEY}/${purpose}` + `${DELIMITER}${coinType}` + `${DELIMITER}${account}` + `${DELIMITER}` + `${hasChange ? change : ''}` }${hasChange && hasAddressIndex ? `/${addressIndex}` : ''}`; }; /** * Recover a public key from a message and the signature of that message. * * @NOTE Further optimization * * This can be further optimized by writing our own recovery mechanism since we already * do most of the cleanup, checking and coversions. * * All that is left to do is to use `secp256k1` to convert and recover the public key * from the signature points (components). * * But since most of our dependencies already use `ethereumjs-util` under the hood anyway, * it's easier just use it as well. * * @method recoverPublicKey * * @param {string} message The message string to hash for the signature verification procedure * @param {string} signature The signature to recover the private key from, as a `hex` string * * All the above params are sent in as props of an {MessageVerificationObjectType} object. * * @return {String} The recovered public key. */ export const recoverPublicKey = ({ message, signature, }: VerifyMessageData): string => { const signatureBuffer = Buffer.from( hexSequenceNormalizer(signature.toLowerCase(), false), HEX_HASH_TYPE, ); const messages = helperMessages.verifyMessageSignature; /* * It should be 65 bits in legth: * - 32 for the (R) point (component) * - 32 for the (S) point (component) * - 1 for the reco(V)ery param */ if (signatureBuffer.length !== 65) { throw new Error(messages.wrongLength); } /* * The recovery param is the the 64th bit of the signature Buffer */ const recoveryParam = recoveryParamNormalizer(signatureBuffer[64]); const rComponent = signatureBuffer.slice(0, 32); const sComponent = signatureBuffer.slice(32, 64); const messageHash = hashPersonalMessage(Buffer.from(message)); /* * Elliptic curve recovery. * * @NOTE `ecrecover` is just a helper method * Around `secp256k1`'s `recover()` and `publicKeyConvert()` methods * * This is to what the function description comment block note is referring to */ const recoveredPublicKeyBuffer = ecrecover( messageHash, recoveryParam, rComponent, sComponent, ); /* * Normalize and return the recovered public key */ return hexSequenceNormalizer( recoveredPublicKeyBuffer.toString(HEX_HASH_TYPE), ); }; /** * Verify a signed message. * By extracting it's public key from the signature and comparing it with a provided one. * * @method verifyMessageSignature * * @param {string} publicKey Public key to check against, as a 'hex' string * @param {string} message The message string to hash for the signature verification procedure * @param {string} signature The signature to recover the private key from, as a `hex` string * * All the above params are sent in as props of an {MessageVerificationObjectType} object. * * @return {boolean} true or false depending if the signature is valid or not * */ export const verifyMessageSignature = ({ publicKey, message, signature, }): boolean => { const { verifyMessageSignature: messages } = helperMessages; try { /* * Normalize the recovered public key by removing the `0x` preifx */ const recoveredPublicKey: string = hexSequenceNormalizer( recoverPublicKey({ message, signature }), false, ); /* * Remove the prefix (0x) and the header (first two bits) from the public key we * want to test against */ const normalizedPublicKey: string = hexSequenceNormalizer( publicKey, false, ).slice(2); /* * Last 64 bits of the private should match the first 64 bits of the recovered public key */ return !!recoveredPublicKey.includes(normalizedPublicKey); } catch (caughtError) { warning(`${messages.somethingWentWrong}. Error: ${caughtError.message}`, { level: 'high', }); return false; } }; /** * Validate an transaction object * * @NOTE We can only validate here, we can't also normalize. This is because different * wallet types expect different value formats so we must normalize them on a case by case basis. * * @method transactionObjectValidator * * @param {bigNumber} gasPrice gas price for the transaction in WEI (as an instance of bigNumber), defaults to 9000000000 (9 GWEI) * @param {bigNumber} gasLimit gas limit for the transaction (as an instance of bigNumber), defaults to 21000 * @param {number} chainId the id of the chain for which this transaction is intended. Defaults to 1 * @param {number} nonce the nonce to use for the transaction (as a number) * @param {string} to the address to which to the transaction is sent * @param {bigNumber} value the value of the transaction in WEI (as an instance of bigNumber), defaults to 1 * @param {string} inputData data appended to the transaction (as a `hex` string) * * All the above params are sent in as props of an {TransactionObjectType} object. * * @return {TransactionObjectType} The validated transaction object containing the exact passed in values */ export const transactionObjectValidator = ({ chainId = TRANSACTION.CHAIN_ID, gasPrice = bigNumber(TRANSACTION.GAS_PRICE), gasLimit = bigNumber(TRANSACTION.GAS_LIMIT), nonce = TRANSACTION.NONCE, to, value = bigNumber(TRANSACTION.VALUE), inputData = TRANSACTION.INPUT_DATA, }: TransactionObjectTypeWithTo): TransactionObjectTypeWithTo => { /* * Check that the gas price is a big number */ bigNumberValidator(gasPrice); /* * Check that the gas limit is a big number */ bigNumberValidator(gasLimit); /* * Check if the chain id value is valid (a positive, safe integer) */ safeIntegerValidator(chainId); /* * Check if the nonce value is valid (a positive, safe integer) */ safeIntegerValidator(nonce); /* * Only check if the address (`to` prop) is in the correct * format, if one was provided in the initial transaction object */ if (to) { addressValidator(to); } /* * Check that the value is a big number */ bigNumberValidator(value); /* * Check that the input data prop is a valid hex string sequence */ hexSequenceValidator(inputData); /* * Normalize the values and return them */ return { gasPrice, gasLimit, chainId, nonce, to, value, inputData, }; }; /** * Validate a signature verification message object * * @method messageVerificationObjectValidator * * @param {string} message The message string to check the signature against * @param {string} signature The signature of the message. * * All the above params are sent in as props of an {MessageVerificationObjectType} object. * * @return {Object} The validated signature object containing the exact passed in values */ export const messageVerificationObjectValidator = ({ /* * For the Ledger wallet implementation we can't pass in an empty string, so * we try with the next best thing. */ message, signature, }: VerifyMessageData): VerifyMessageData => { /* * Check if the messages is in the correct format */ messageValidator(message); /* * Check if the signature is in the correct format */ hexSequenceValidator(signature); return { message, /* * Ensure the signature has the hex `0x` prefix */ signature: hexSequenceNormalizer(signature), }; }; /** * Check if the user provided input is in the form of an Object and it's required props * * @method userInputValidator * * @param {Object} firstArgument The argument to validate that it's indeed an object, and that it has the required props * @param {Array} requiredEither Array of strings representing prop names of which at least one is required. * @param {Array} requiredAll Array of strings representing prop names of which all are required. * * All the above params are sent in as props of an object. */ export const userInputValidator = ({ firstArgument = {}, requiredEither = [], requiredAll = [], requiredOr = [], }: { // eslint-disable-next-line @typescript-eslint/no-explicit-any firstArgument?: Record<string, any>; requiredEither?: Array<string>; requiredAll?: Array<string>; requiredOr?: Array<string>; } = {}): void => { const { userInputValidator: messages } = helperMessages; /* * First we check if the argument is an Object (also, not an Array) */ if (typeof firstArgument !== 'object' || Array.isArray(firstArgument)) { /* * Explain the arguments format (if we're in dev mode), then throw the Error */ warning(messages.argumentsFormatExplanation); throw new Error(messages.notObject); } /* * Check if some of the required props are available * Fail if none are available. */ if (requiredEither && requiredEither.length) { const availableProps: Array<boolean> = requiredEither.map((propName) => Object.prototype.hasOwnProperty.call(firstArgument, propName), ); if (!availableProps.some((propExists) => propExists === true)) { /* * Explain the arguments format (if we're in dev mode), then throw the Error */ warning(messages.argumentsFormatExplanation); throw new Error( `${messages.notSomeProps}: { '${requiredEither.join(`', '`)}' }`, ); } } /* * Check if all required props are present. * Fail after the first one missing. */ if (requiredAll) { requiredAll.map((propName) => { if (!Object.prototype.hasOwnProperty.call(firstArgument, propName)) { /* * Explain the arguments format (if we're in dev mode), then throw the Error */ warning(messages.argumentsFormatExplanation); throw new Error( `${messages.notAllProps}: { '${requiredAll.join(`', '`)}' }`, ); } return propName; }); } /* * Check if exactly one of the required props is present. * Fail if multiple are present. */ if ( requiredOr && requiredOr.length && requiredOr.reduce( (acc, propName) => Object.prototype.hasOwnProperty.call(firstArgument, propName) ? acc + 1 : acc, 0, ) !== 1 ) { warning(messages.argumentsFormatExplanation); throw new Error(); } }; export const messageOrDataValidator = ({ message, messageData, }: { message: string; messageData: string | Uint8Array; }): string | Uint8Array => { if (message) { messageValidator(message); return message; } messageDataValidator(messageData); return typeof messageData === 'string' ? new Uint8Array( Buffer.from(hexSequenceNormalizer(messageData, false), 'hex'), ) : messageData; }; /** * In order to support EIP-155, it's necessary to specify various * definitions for a given chain (e.g. the chain ID, network ID, hardforks). * * Given a chain ID, this function returns a chain definition in the format * expected by `ethereumjs-common`. * * @param {number} chainId The given chain ID (as defined in EIP-155) * @return {Object} The common chain definition */ export const getChainDefinition = (chainId: number): TransactionOptions => { let baseChain: string; switch (chainId) { /* * Ganache's default chain ID is 1337, and is also the standard for * private chains. The assumption is taken here that this inherits * all of the other properties from mainnet, but that might not be * the case. * * @TODO Provide a means to specify all chain properties for transactions */ case CHAIN_IDS.HOMESTEAD: case CHAIN_IDS.LOCAL: { baseChain = NETWORK_NAMES.MAINNET; break; } case CHAIN_IDS.GOERLI: { baseChain = NETWORK_NAMES.GOERLI; break; } /* * The following (or other) chain IDs _may_ cause validation errors * in `ethereumjs-common` */ case CHAIN_IDS.KOVAN: { baseChain = NETWORK_NAMES.KOVAN; break; } case CHAIN_IDS.ROPSTEN: { baseChain = NETWORK_NAMES.ROPSTEN; break; } case CHAIN_IDS.RINKEBY: { baseChain = NETWORK_NAMES.RINKEBY; break; } default: { baseChain = chainId.toString(); } } return { common: Common.forCustomChain( baseChain, { chainId }, /* * `ethereumjs-common` requires a hardfork to be defined, so we are * using the current default for this property. This is also an * assumption, and this should be made configurable. */ HARDFORKS.PETERSBURG, ), }; };
the_stack
import { css } from '@emotion/react'; import { light, Theme } from '@sumup/design-tokens'; import { create } from '../util/test-utils'; import { cx, spacing, shadow, typography, disableVisually, hideVisually, focusOutline, focusVisible, clearfix, hideScrollbar, inputOutline, listItem, navigationItem, center, } from './style-mixins'; describe('Style helpers', () => { const red = (theme: Theme) => css` color: ${theme.colors.r500}; `; const green = (theme: Theme) => css` color: ${theme.colors.g500}; `; const purple = css` color: rebeccapurple; `; describe('cx', () => { it('should call each style function with the theme', () => { const actual = create(<div css={cx(red, green)} />); expect(actual).toMatchInlineSnapshot(` .circuit-0 { color: #D23F47; color: #8CC13F; } <div class="circuit-0" /> `); }); it('should support style objects', () => { const actual = create(<div css={cx(purple)} />); expect(actual).toMatchInlineSnapshot(` .circuit-0 { color: rebeccapurple; } <div class="circuit-0" /> `); }); it('should skip falsy style functions', () => { const isGreen = false; const actual = create(<div css={cx(red, isGreen && green)} />); expect(actual).toMatchInlineSnapshot(` .circuit-0 { color: #D23F47; } <div class="circuit-0" /> `); }); }); describe('spacing', () => { it('should apply spacing to four sides when passing a string', () => { const { styles } = spacing('mega')(light); expect(styles).toMatchInlineSnapshot('"margin:16px;;label:spacing;"'); }); it('should apply individual spacing for one side when passing an object', () => { const { styles } = spacing({ bottom: 'kilo' })(light); expect(styles).toMatchInlineSnapshot( '"margin-bottom:12px;;label:spacing;"', ); }); it('should apply individual spacing to each sides when passing all four values in an object', () => { const { styles } = spacing({ top: 'kilo', right: 'mega', left: 'giga', bottom: 'kilo', })(light); expect(styles).toMatchInlineSnapshot( '"margin-top:12px;margin-right:16px;margin-bottom:12px;margin-left:24px;;label:spacing;"', ); }); it('should apply 0px spacing to one side when passing 0 value in an object', () => { const { styles } = spacing({ top: 0, right: 'mega', left: 'giga', bottom: 'kilo', })(light); expect(styles).toMatchInlineSnapshot( '"margin-top:0;margin-right:16px;margin-bottom:12px;margin-left:24px;;label:spacing;"', ); }); it('should support `0` spacing value', () => { const { styles } = spacing(0)(light); expect(styles).toMatchInlineSnapshot('"margin:0;;label:spacing;"'); }); it('should support the `auto` spacing value', () => { const { styles } = spacing('auto')(light); expect(styles).toMatchInlineSnapshot('"margin:auto;;label:spacing;"'); }); }); describe('shadow', () => { it('should match the snapshot', () => { const { styles } = shadow({ theme: light }); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 3px 8px 0 rgba(0, 0, 0, 0.2);label:shadow;"', ); }); it('should match the snapshot with options', () => { const { styles } = shadow()({ theme: light }); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 3px 8px 0 rgba(0, 0, 0, 0.2);label:shadow;"', ); }); }); describe('typography', () => { it('should match the snapshot for size one', () => { const { styles } = typography('one')(light); expect(styles).toMatchInlineSnapshot( '"font-size:16px;line-height:24px;;label:typography;"', ); }); it('should match the snapshot for size two', () => { const { styles } = typography('two')(light); expect(styles).toMatchInlineSnapshot( '"font-size:14px;line-height:20px;;label:typography;"', ); }); }); describe('disableVisually', () => { it('should match the snapshot', () => { const { styles } = disableVisually(); expect(styles).toMatchInlineSnapshot( '"opacity:0.5;pointer-events:none;box-shadow:none;label:disableVisually;"', ); }); }); describe('hideVisually', () => { it('should match the snapshot', () => { const { styles } = hideVisually(); expect(styles).toMatchInlineSnapshot( '"border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;white-space:nowrap;width:1px;label:hideVisually;"', ); }); }); describe('center', () => { it('should match the snapshot', () => { const { styles } = center(); expect(styles).toMatchInlineSnapshot( '"display:flex;flex-direction:column;justify-content:center;align-items:center;label:center;"', ); }); }); describe('focusOutline', () => { it('should match the snapshot', () => { const { styles } = focusOutline({ theme: light }); expect(styles).toMatchInlineSnapshot( '"outline:0;box-shadow:0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;};label:focusOutline;"', ); }); it('should match the snapshot with an inset outline', () => { const { styles } = focusOutline('inset')({ theme: light }); expect(styles).toMatchInlineSnapshot( '"outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;};label:focusOutline;"', ); }); }); describe('focusVisible', () => { it('should match the snapshot', () => { const { styles } = focusVisible({ theme: light }); expect(styles).toMatchInlineSnapshot( '"&:focus{outline:0;box-shadow:0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;"', ); }); it('should match the snapshot with an inset outline', () => { const { styles } = focusVisible('inset')({ theme: light }); expect(styles).toMatchInlineSnapshot( '"&:focus{outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;"', ); }); }); describe('clearfix', () => { it('should match the snapshot', () => { const { styles } = clearfix(); expect(styles).toMatchInlineSnapshot( '"&::before,&::after{content:\' \';display:table;}&::after{clear:both;};label:clearfix;"', ); }); }); describe('hideScrollbar', () => { it('should match the snapshot', () => { const { styles } = hideScrollbar(); expect(styles).toMatchInlineSnapshot( '"-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;};label:hideScrollbar;"', ); }); }); describe('inputOutline', () => { it('should match the snapshot', () => { const { styles } = inputOutline(light); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 0 0 1px #999;&:hover{box-shadow:0 0 0 1px #666;}&:focus{box-shadow:0 0 0 2px #3063E9;}&:active{box-shadow:0 0 0 1px #3063E9;};label:inputOutline;"', ); }); it('should match the snapshot when disabled', () => { const { styles } = inputOutline({ theme: light, disabled: true, }); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 0 0 1px #999;;label:inputOutline;"', ); }); it('should match the snapshot when invalid', () => { const { styles } = inputOutline({ theme: light, invalid: true, }); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 0 0 1px #D23F47;&:hover{box-shadow:0 0 0 1px #B22426;}&:focus{box-shadow:0 0 0 2px #D23F47;}&:active{box-shadow:0 0 0 1px #D23F47;};label:inputOutline;"', ); }); it('should match the snapshot when it has a warning', () => { const { styles } = inputOutline({ theme: light, hasWarning: true, }); expect(styles).toMatchInlineSnapshot( '"box-shadow:0 0 0 1px #F5C625;&:hover{box-shadow:0 0 0 1px #AD7A14;}&:focus{box-shadow:0 0 0 2px #F5C625;}&:active{box-shadow:0 0 0 1px #F5C625;};label:inputOutline;"', ); }); }); describe('listItem', () => { it('should match the snapshot', () => { const { styles } = listItem(light); expect(styles).toMatchInlineSnapshot( '"background-color:#FFF;padding:12px 32px 12px 16px;border:0;color:#1A1A1A;text-decoration:none;position:relative;&:hover{background-color:#F5F5F5;cursor:pointer;}&:focus{outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;;;&:active{background-color:#E6E6E6;}&:disabled,&[disabled]{opacity:0.5;pointer-events:none;box-shadow:none;label:disableVisually;;;};label:listItem;"', ); }); it('should match the snapshot when it is destructive', () => { const { styles } = listItem({ theme: light, destructive: true, }); expect(styles).toMatchInlineSnapshot( '"background-color:#FFF;padding:12px 32px 12px 16px;border:0;color:#D23F47;text-decoration:none;position:relative;&:hover{background-color:#F5F5F5;cursor:pointer;}&:focus{outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;;;&:active{background-color:#E6E6E6;}&:disabled,&[disabled]{opacity:0.5;pointer-events:none;box-shadow:none;label:disableVisually;;;};label:listItem;"', ); }); }); describe('navigationItem', () => { it('should match the snapshot', () => { const { styles } = navigationItem(light); expect(styles).toMatchInlineSnapshot( '"display:flex;align-items:center;border:none;outline:none;color:#1A1A1A;background-color:#FFF;text-align:left;cursor:pointer;transition:color 120ms ease-in-out,background-color 120ms ease-in-out;&:hover{background-color:#F5F5F5;}&:active{background-color:#E6E6E6;}&:focus{outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;;;&:disabled{opacity:0.5;pointer-events:none;box-shadow:none;label:disableVisually;;;};label:navigationItem;"', ); }); it('should match the snapshot when it is active', () => { const { styles } = navigationItem({ theme: light, isActive: true, }); expect(styles).toMatchInlineSnapshot( '"display:flex;align-items:center;border:none;outline:none;color:#3063E9;background-color:#F0F6FF;text-align:left;cursor:pointer;transition:color 120ms ease-in-out,background-color 120ms ease-in-out;&:hover{background-color:#F0F6FF;}&:active{background-color:#E6E6E6;}&:focus{outline:0;box-shadow:inset 0 0 0 4px #AFD0FE;&::-moz-focus-inner{border:0;}}&:focus:not(:focus-visible){box-shadow:none;};label:focusVisible;;;&:disabled{opacity:0.5;pointer-events:none;box-shadow:none;label:disableVisually;;;};label:navigationItem;"', ); }); }); });
the_stack
import {wx, App, Page, getApp, setTimeout, clearTimeout, setInterval, clearInterval} from 'weapp-api' App({ onLaunch: function () { //调用API从本地缓存中获取数据 let logs = wx.getStorageSync('logs') as Array<any> || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) }, getUserInfo: function (cb: Function) { let that = this; if (this.globalData.userInfo) { typeof cb == "function" && cb(this.globalData.userInfo) } else { //调用登录接口 wx.login({ success: function () { wx.getUserInfo({ success: function (res: any) { that.globalData.userInfo = res.userInfo; typeof cb == "function" && cb(that.globalData.userInfo) } }) } }); } }, globalData: { userInfo: null } }) let app = getApp(); let page = app.getCurrentPage(); page.setData({ 'foo': 'bar' }); Page({ data: { foo: 'bar' }, onLoad: function (options) { } }) wx.request({ url: 'test.php', data: { x: '', y: '' }, header: { 'Content-Type': 'application/json' }, success: function (res: any) { console.log(res.data) } }) wx.chooseImage({ success: function (res: any) { var tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'http://example.com/upload', filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' } }) } }) wx.downloadFile({ url: 'http://example.com/audio/123', type: 'audio', success: function (res: any) { wx.playVoice({ filePath: res.tempFilePath }) } }) wx.connectSocket({ url: 'test.php', data: { x: '', y: '' }, header: { 'content-type': 'application/json' }, method: "GET", }) wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res: any) { console.log('WebSocket连接已打开!') }) wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res: any) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res: any) { console.log('WebSocket连接打开失败,请检查!') }) var socketOpen = false var socketMsgQueue: Array<string> = [] wx.connectSocket({ url: 'test.php' }) wx.onSocketOpen(function (res: any) { socketOpen = true for (var i = 0; i < socketMsgQueue.length; i++) { sendSocketMessage(socketMsgQueue[i]) } socketMsgQueue = [] }) function sendSocketMessage(msg: string) { if (socketOpen) { wx.sendSocketMessage({ data: msg }) } else { socketMsgQueue.push(msg) } } wx.connectSocket({ url: 'test.php' }) wx.onSocketMessage(function (res: any) { console.log('收到服务器内容:' + res.data) }) wx.connectSocket({ url: 'test.php' }) //注意这里有时序问题, //如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。 //必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。 wx.onSocketOpen(function () { wx.closeSocket() }) wx.onSocketClose(function (res: any) { console.log('WebSocket 已关闭!') }) wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res: any) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths } }) wx.previewImage({ current: '', // 当前显示图片的http链接 urls: [] // 需要预览的图片http链接列表 }) wx.startRecord({ success: function (res: any) { var tempFilePath = res.tempFilePath }, fail: function (res: any) { //录音失败 } }) setTimeout(function () { //结束录音 wx.stopRecord() }, 10000) wx.startRecord({ success: function (res: any) { var tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath, complete: function () { } }) } }) wx.startRecord({ success: function (res: any) { var tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath }) setTimeout(function () { //暂停播放 wx.pauseVoice() }, 5000) } }) wx.startRecord({ success: function (res: any) { var tempFilePath = res.tempFilePath wx.playVoice({ filePath: tempFilePath }) setTimeout(function () { wx.stopVoice() }, 5000) } }) wx.getBackgroundAudioPlayerState({ success: function (res: any) { var status = res.status var dataUrl = res.dataUrl var currentPosition = res.currentPosition var duration = res.duration var downloadPercent = res.downloadPercent } }) wx.playBackgroundAudio({ dataUrl: '', title: '', coverImgUrl: '' }) wx.pauseBackgroundAudio() wx.seekBackgroundAudio({ position: 30 }) wx.stopBackgroundAudio() wx.startRecord({ success: function (res: any) { var tempFilePath = res.tempFilePath wx.saveFile({ tempFilePath: tempFilePath, success: function (res: any) { var savedFilePath = res.savedFilePath } }) } }) Page({ bindButtonTap: function () { var that = this wx.chooseVideo({ sourceType: ['album', 'camera'], maxDuration: 60, camera: ['front', 'back'], success: function (res: any) { that.setData({ src: res.tempFilePath }) } }) } }) wx.setStorage({ key: "key", data: "value" }) try { wx.setStorageSync('key', 'value') } catch (e) { } wx.getStorage({ key: 'key', success: function (res: any) { console.log(res.data) } }) var value = wx.getStorageSync('key') if (value) { // Do something with return value } wx.clearStorage() try { wx.clearStorageSync() } catch (e) { } wx.getLocation({ type: 'wgs84', success: function (res: any) { var latitude = res.latitude var longitude = res.longitude var speed = res.speed var accuracy = res.accuracy } }) wx.getLocation({ type: 'gcj02', //返回可以用于wx.openLocation的经纬度 success: function(res: any) { var latitude = res.latitude var longitude = res.longitude wx.openLocation({ latitude: latitude, longitude: longitude, scale: 28 }) } }) wx.getNetworkType({ success: function(res: any) { var networkType = res.networkType // 返回网络类型2g,3g,4g,wifi } }) wx.getSystemInfo({ success: function(res: any) { console.log(res.model) console.log(res.pixelRatio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) } }) const updateManager = wx.getUpdateManager() // updateManager.onCheckForUpdate(function (res: any) { // //请求完新版本信息的回调 // console.log(res.hasUpdate) // }) updateManager.onUpdateReady(function () { // wx.showModal({ // title: '更新提示', // content: '新版本已经准备好,是否重启应用?', // success(res: any) { // if (res.confirm) { // // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 // updateManager.applyUpdate() // } // } // }) }) updateManager.onUpdateFailed(function () { // 新版本下载失败 }) wx.onAccelerometerChange(function(res: any) { console.log(res.x) console.log(res.y) console.log(res.z) }) wx.onCompassChange(function (res: any) { console.log(res.direction) }) wx.setNavigationBarTitle({ title: '当前页面' }) wx.navigateTo({ url: 'test?id=1' }) wx.redirectTo({ url: 'test?id=1' }) var animation = wx.createAnimation({ transformOrigin: "50% 50%", duration: 1000, timingFunction: "ease", delay: 0 }) Page({ data: { animationData: {} }, onShow: function(){ var animation = wx.createAnimation({ duration: 1000, timingFunction: 'ease', }) this.animation = animation animation.scale(2,2).rotate(45).step() this.setData({ animationData:animation.export() }) setTimeout(function() { animation.translate(30).step() this.setData({ animationData:animation.export() }) }, 1000) }, rotateAndScale: function () { // 旋转同时放大 this.animation.rotate(45).scale(2, 2).step() this.setData({ animationData:animation.export() }) }, rotateThenScale: function () { // 先旋转后放大 this.animation.rotate(45).step() this.animation.scale(2, 2).step() this.setData({ animationData:animation.export() }) }, rotateAndScaleThenTranslate: function () { // 先旋转同时放大,然后平移 this.animation.rotate(45).scale(2, 2).step() this.animation.translate(100, 100).step({ duration: 1000 }) this.setData({ animationData:animation.export() }) } }) // 假设页面上有3个画布 var canvas1Id = 3001 var canvas2Id = 3002 var canvas3Id = 3003 var context = wx.createContext(); [canvas1Id, canvas2Id, canvas3Id].forEach(function (id) { context.clearActions() // 在context上调用方法 wx.drawCanvas({ canvasId: id, actions: context.getActions() }) }) Page({ onReady: function() { var context = wx.createContext() context.rect(5, 5, 25, 15) context.stroke() context.scale(2, 2) //再放大2倍 context.rect(5, 5, 25, 15) context.stroke() context.scale(2, 2) //再放大2倍 context.rect(5, 5, 25, 15) context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }) } }) Page({ onReady: function() { var context = wx.createContext() context.rect(50, 50, 200, 200) context.stroke() context.rotate(5 * Math.PI / 180) context.rect(50, 50, 200, 200) context.stroke() context.rotate(5 * Math.PI / 180) context.rect(50, 50, 200, 200) context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }) } }) Page({ onReady: function() { var context = wx.createContext() context.rect(50, 50, 200, 200) context.stroke() context.translate(50, 50) context.rect(50, 50, 200, 200) context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }) } }) Page({ onReady: function() { var context = wx.createContext() context.rect(50, 50, 200, 200) context.fill() context.clearRect(100, 100, 50, 50) wx.drawCanvas({ canvasId: 1, actions: context.getActions() }) } }) Page({ onReady: function() { var context = wx.createContext() wx.chooseImage({ success: function(res: any) { context.drawImage(res.tempFilePaths[0], 0, 0) wx.drawCanvas({ canvasId: 1, actions: context.getActions() }) } }) } }) Page({ onReady:function(){ var context = wx.createContext() context.setFontSize(14) context.fillText("MINA", 50, 50) context.moveTo(0, 50) context.lineTo(100, 50) context.stroke() context.setFontSize(20) context.fillText("MINA", 100, 100) context.moveTo(0, 100) context.lineTo(200, 100) context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }); } }) Page({ onReady: function() { var context = wx.createContext() context.setFillStyle("#ff00ff") context.setStrokeStyle("#00ffff") context.rect(50, 50, 100, 100) context.fill() context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }); } }) Page({ onReady: function() { var context = wx.createContext() context.setLineWidth(10) context.setLineCap("round") context.setLineJoin("miter") context.setMiterLimit(10) context.moveTo(20, 20) context.lineTo(150, 27) context.lineTo(20, 54) context.stroke() context.beginPath() context.setMiterLimit(3) context.moveTo(20, 70) context.lineTo(150, 77) context.lineTo(20, 104) context.stroke() wx.drawCanvas({ canvasId: 1, actions: context.getActions() }); } }) Page({ canvasIdErrorCallback: function (e:any) { console.error(e.detail.errMsg) }, onReady: function() { //使用wx.createContext获取绘图上下文context var context = wx.createContext() context.setStrokeStyle("#00ff00") context.setLineWidth(5) context.rect(0, 0, 200, 200) context.stroke() context.setStrokeStyle("#ff0000") context.setLineWidth(2) context.moveTo(160, 100) context.arc(100, 100, 60, 0,2 * Math.PI, true) context.moveTo(140, 100) context.arc(100, 100, 40, 0, Math.PI, false) context.moveTo(85, 80) context.arc(80, 80, 5, 0,2 * Math.PI, true) context.moveTo(125, 80) context.arc(120, 80, 5, 0, 2 * Math.PI, true) context.stroke() // 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为 wx.drawCanvas({ canvasId: 'firstCanvas', actions: context.getActions() // 获取绘图动作数组 }) } }) App({ onLaunch: function() { wx.login({ success: function(res: any) { if (res.code) { //发起网络请求 wx.request({ url: 'https://test.com/onLogin', data: { code: res.code } }) } else { console.log('获取用户登录态失败!' + res.errMsg) } } }); } }) wx.getUserInfo({ success: function(res: any) { var userInfo = res.userInfo var nickName = userInfo.nickName var avatarUrl = userInfo.avatarUrl var gender = userInfo.gender //性别 0:未知、1:男、2:女 var province = userInfo.province var city = userInfo.city var country = userInfo.country } }) wx.requestPayment({ 'timeStamp': '', 'nonceStr': '', 'package': '', 'signType': 'MD5', 'paySign': '', 'success':function(res: any){ }, 'fail':function(res: any){ } }) App({ onLaunch(options){ console.log(options.query) } })
the_stack
import {AbstractMessageParser} from './abstract-message-parser'; import {ParsedMessage} from './parsed-message'; import {ParsedMessagePartStartTag} from './parsed-message-part-start-tag'; import {ParsedMessagePartEndTag} from './parsed-message-part-end-tag'; import {ParsedMessagePartPlaceholder} from './parsed-message-part-placeholder'; import {ParsedMessagePartText} from './parsed-message-part-text'; import {ParsedMessagePartType} from './parsed-message-part'; import {TagMapping} from './tag-mapping'; import {ParsedMessagePartEmptyTag} from './parsed-message-part-empty-tag'; import {ParsedMessagePartICUMessageRef} from './parsed-message-part-icu-message-ref'; /** * Created by roobm on 10.05.2017. * A message parser for XLIFF 2.0 */ export class Xliff2MessageParser extends AbstractMessageParser { /** * Handle this element node. * This is called before the children are done. * @param elementNode elementNode * @param message message to be altered * @return true, if children should be processed too, false otherwise (children ignored then) */ protected processStartElement(elementNode: Element, message: ParsedMessage): boolean { const tagName = elementNode.tagName; if (tagName === 'ph') { // placeholder are like <ph id="0" equiv="INTERPOLATION" disp="{{number()}}"/> // They contain the id and also a name (number in the example) // TODO make some use of the name (but it is not available in XLIFF 1.2) // ICU message are handled with the same tag // Before 4.3.2 they did not have an equiv and disp (Bug #17344): // e.g. <ph id="0"/> // Beginning with 4.3.2 they do have an equiv ICU and disp: // e.g. <ph id="0" equiv="ICU" disp="{count, plural, =0 {...} =1 {...} other {...}}"/> // and empty tags have equiv other then INTERPOLATION: // e.g. <ph id="3" equiv="TAG_IMG" type="image" disp="&lt;img/>"/> // or <ph equiv="LINE_BREAK" type="lb" disp="&lt;br/>"/> let isInterpolation = false; let isICU = false; let isEmptyTag = false; const equiv = elementNode.getAttribute('equiv'); const disp = elementNode.getAttribute('disp'); let indexString = null; let index = 0; let emptyTagName = null; if (!equiv) { // old ICU syntax, fixed with #17344 isICU = true; indexString = elementNode.getAttribute('id'); index = Number.parseInt(indexString, 10); } else if (equiv.startsWith('ICU')) { // new ICU syntax, fixed with #17344 isICU = true; if (equiv === 'ICU') { indexString = '0'; } else { indexString = equiv.substring('ICU_'.length); } index = Number.parseInt(indexString, 10); } else if (equiv.startsWith('INTERPOLATION')) { isInterpolation = true; if (equiv === 'INTERPOLATION') { indexString = '0'; } else { indexString = equiv.substring('INTERPOLATION_'.length); } index = Number.parseInt(indexString, 10); } else if (new TagMapping().isEmptyTagPlaceholderName(equiv)) { isEmptyTag = true; emptyTagName = new TagMapping().getTagnameFromEmptyTagPlaceholderName(equiv); } else { return true; } if (isInterpolation) { message.addPlaceholder(index, disp); } else if (isICU) { message.addICUMessageRef(index, disp); } else if (isEmptyTag) { message.addEmptyTag(emptyTagName, this.parseIdCountFromName(equiv)); } } else if (tagName === 'pc') { // pc example: <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" // dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">IMPORTANT</pc> const embeddedTagName = this.tagNameFromPCElement(elementNode); if (embeddedTagName) { message.addStartTag(embeddedTagName, this.parseIdCountFromName(elementNode.getAttribute('equivStart'))); } } return true; } /** * Handle end of this element node. * This is called after all children are processed. * @param elementNode elementNode * @param message message to be altered */ protected processEndElement(elementNode: Element, message: ParsedMessage) { const tagName = elementNode.tagName; if (tagName === 'pc') { // pc example: <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" // dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;">IMPORTANT</pc> const embeddedTagName = this.tagNameFromPCElement(elementNode); if (embeddedTagName) { message.addEndTag(embeddedTagName); } return; } } private tagNameFromPCElement(pcNode: Element): string { let dispStart = pcNode.getAttribute('dispStart'); if (dispStart.startsWith('<')) { dispStart = dispStart.substring(1); } if (dispStart.endsWith('>')) { dispStart = dispStart.substring(0, dispStart.length - 1); } return dispStart; } /** * reimplemented here, because XLIFF 2.0 uses a deeper xml model. * So we cannot simply replace the message parts by xml parts. * @param message message * @param rootElem rootElem */ protected addXmlRepresentationToRoot(message: ParsedMessage, rootElem: Element) { const stack = [{element: rootElem, tagName: 'root'}]; let id = 0; message.parts().forEach((part) => { switch (part.type) { case ParsedMessagePartType.TEXT: stack[stack.length - 1].element.appendChild( this.createXmlRepresentationOfTextPart(<ParsedMessagePartText> part, rootElem)); break; case ParsedMessagePartType.PLACEHOLDER: stack[stack.length - 1].element.appendChild( this.createXmlRepresentationOfPlaceholderPart(<ParsedMessagePartPlaceholder> part, rootElem, id++)); break; case ParsedMessagePartType.ICU_MESSAGE_REF: stack[stack.length - 1].element.appendChild( this.createXmlRepresentationOfICUMessageRefPart(<ParsedMessagePartICUMessageRef> part, rootElem)); break; case ParsedMessagePartType.START_TAG: const newTagElem = this.createXmlRepresentationOfStartTagPart(<ParsedMessagePartStartTag> part, rootElem, id++); stack[stack.length - 1].element.appendChild(newTagElem); stack.push({element: <Element> newTagElem, tagName: (<ParsedMessagePartStartTag> part).tagName()}); break; case ParsedMessagePartType.END_TAG: const closeTagName = (<ParsedMessagePartEndTag> part).tagName(); if (stack.length <= 1 || stack[stack.length - 1].tagName !== closeTagName) { // oops, not well formed throw new Error('unexpected close tag ' + closeTagName); } stack.pop(); break; case ParsedMessagePartType.EMPTY_TAG: const emptyTagElem = this.createXmlRepresentationOfEmptyTagPart(<ParsedMessagePartEmptyTag> part, rootElem, id++); stack[stack.length - 1].element.appendChild(emptyTagElem); break; } }); if (stack.length !== 1) { // oops, not well closed tags throw new Error('missing close tag ' + stack[stack.length - 1].tagName); } } /** * the xml used for start tag in the message. * Returns an empty pc-Element. * e.g. <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"> * Text content will be added later. * @param part part * @param rootElem rootElem * @param id id number in xliff2 */ protected createXmlRepresentationOfStartTagPart(part: ParsedMessagePartStartTag, rootElem: Element, id: number): Node { const tagMapping = new TagMapping(); const pcElem = rootElem.ownerDocument.createElement('pc'); const tagName = part.tagName(); const equivStart = tagMapping.getStartTagPlaceholderName(tagName, part.idCounter()); const equivEnd = tagMapping.getCloseTagPlaceholderName(tagName); const dispStart = '<' + tagName + '>'; const dispEnd = '</' + tagName + '>'; pcElem.setAttribute('id', id.toString(10)); pcElem.setAttribute('equivStart', equivStart); pcElem.setAttribute('equivEnd', equivEnd); pcElem.setAttribute('type', this.getTypeForTag(tagName)); pcElem.setAttribute('dispStart', dispStart); pcElem.setAttribute('dispEnd', dispEnd); return pcElem; } /** * the xml used for end tag in the message. * Not used here, because content is child of start tag. * @param part part * @param rootElem rootElem */ protected createXmlRepresentationOfEndTagPart(part: ParsedMessagePartEndTag, rootElem: Element): Node { // not used return null; } /** * the xml used for empty tag in the message. * Returns an empty ph-Element. * e.g. <ph id="3" equiv="TAG_IMG" type="image" disp="&lt;img/>"/> * @param part part * @param rootElem rootElem * @param id id number in xliff2 */ protected createXmlRepresentationOfEmptyTagPart(part: ParsedMessagePartEmptyTag, rootElem: Element, id: number): Node { const tagMapping = new TagMapping(); const phElem = rootElem.ownerDocument.createElement('ph'); const tagName = part.tagName(); const equiv = tagMapping.getEmptyTagPlaceholderName(tagName, part.idCounter()); const disp = '<' + tagName + '/>'; phElem.setAttribute('id', id.toString(10)); phElem.setAttribute('equiv', equiv); phElem.setAttribute('type', this.getTypeForTag(tagName)); phElem.setAttribute('disp', disp); return phElem; } private getTypeForTag(tag: string): string { switch (tag.toLowerCase()) { case 'br': case 'b': case 'i': case 'u': return 'fmt'; case 'img': return 'image'; case 'a': return 'link'; default: return 'other'; } } /** * the xml used for placeholder in the message. * Returns e.g. <ph id="1" equiv="INTERPOLATION_1" disp="{{total()}}"/> * @param part part * @param rootElem rootElem * @param id id number in xliff2 */ protected createXmlRepresentationOfPlaceholderPart(part: ParsedMessagePartPlaceholder, rootElem: Element, id: number): Node { const phElem = rootElem.ownerDocument.createElement('ph'); let equivAttrib = 'INTERPOLATION'; if (part.index() > 0) { equivAttrib = 'INTERPOLATION_' + part.index().toString(10); } phElem.setAttribute('id', id.toString(10)); phElem.setAttribute('equiv', equivAttrib); const disp = part.disp(); if (disp) { phElem.setAttribute('disp', disp); } return phElem; } /** * the xml used for icu message refs in the message. * @param part part * @param rootElem rootElem */ protected createXmlRepresentationOfICUMessageRefPart(part: ParsedMessagePartICUMessageRef, rootElem: Element): Node { const phElem = rootElem.ownerDocument.createElement('ph'); let equivAttrib = 'ICU'; if (part.index() > 0) { equivAttrib = 'ICU_' + part.index().toString(10); } phElem.setAttribute('id', part.index().toString(10)); phElem.setAttribute('equiv', equivAttrib); const disp = part.disp(); if (disp) { phElem.setAttribute('disp', disp); } return phElem; } }
the_stack
import type { TokenEachCheck } from '../../token/token-collection'; import { log } from '../../debug'; import { matched, unmatched } from '../../match-result'; export const datetimeTokenCheck: Record< | 'year' | 'month' | 'date' | 'hour' | 'minute' | 'second' | 'secondFractionalPart' | 'week' | 'hyphen' | 'coron' | 'extra' | 'coronOrEnd' | 'decimalPointOrEnd' | 'localDateTimeSeparator' | 'normalizedlocalDateTimeSeparator' | 'plusOrMinusSign' | 'weekSign', TokenEachCheck > & Record<'_year' | '_month', number | null> = { /** * Temporary year state */ _year: null, /** * Temporary month state */ _month: null, /** * > Four or more ASCII digits, representing year, where year > 0 */ year(year) { log('Parsing Datetime Year: "%s"', year?.value); this._year = null; if (!year || !year.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'year' }], partName: 'year', }); } if (!year.match(/^[0-9]+$/)) { return year.unmatched({ reason: 'unexpected-token', expects: [], partName: 'year', }); } if (year.length < 4) { return year.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 4 }, expects: [], partName: 'year', }); } this._year = year.toNumber(); if (this._year <= 0) { return year.unmatched({ reason: { type: 'out-of-range', gt: 0 }, expects: [], partName: 'year', }); } }, /** * > Two ASCII digits, representing the month month, in the range 1 ≤ month ≤ 12 */ month(month) { log('Parsing Datetime Month: "%s"', month?.value); this._month = null; if (!month || !month.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'month' }], partName: 'month', }); } if (!month.match(/^[0-9]+$/)) { return month.unmatched({ reason: 'unexpected-token', expects: [], partName: 'month', }); } if (month.length !== 2) { return month.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'month', }); } this._month = month.toNumber(); if (!(1 <= this._month && this._month <= 12)) { return month.unmatched({ reason: { type: 'out-of-range', gte: 1, lte: 12 }, expects: [], partName: 'month', }); } }, /** * > Two ASCII digits, representing day, in the range 1 ≤ day ≤ maxday where maxday is the number of days in the month month and year year * * or * * In Yearless dates, * > Two ASCII digits, representing day, * > in the range 1 ≤ day ≤ maxday where maxday is the number of days * > in the month month and any arbitrary leap year (e.g. 4 or 2000) * > In other words, if the month is "02", meaning February, * > then the day can be 29, as if the year was a leap year. */ date(date) { log('Parsing Datetime Date: "%s"', date?.value); if (!date || !date.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'date' }], partName: 'date', }); } if (!date.match(/^[0-9]+$/)) { return date.unmatched({ reason: 'unexpected-token', expects: [], partName: 'date', }); } if (date.length !== 2) { return date.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'date', }); } // Set the leap year if _year is null const year = this._year || 2000; const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; const month = this._month || 1; const dayOfMonth = daysOfMonth[month] + (month === 2 && isLeap ? 1 : 0); const _date = date.toNumber(); log('Temporary Year and Month: %s, %s', this._year, this._month); log('Computed Year, Month, and Day of Month: %s, %s, %s', year, month, dayOfMonth); if (!(1 <= _date && _date <= dayOfMonth)) { return date.unmatched({ reason: { type: 'out-of-range', gte: 1, lte: dayOfMonth }, expects: [], partName: 'date', }); } }, /** * > Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23 */ hour(hour) { log('Parsing Datetime Hour: "%s"', hour?.value); if (!hour || !hour.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'hour' }], partName: 'hour', }); } if (!hour.match(/^[0-9]+$/)) { return hour.unmatched({ reason: 'unexpected-token', expects: [], partName: 'hour', }); } if (hour.length !== 2) { return hour.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'hour', }); } const _hour = hour.toNumber(); if (!(0 <= _hour && _hour <= 23)) { return hour.unmatched({ reason: { type: 'out-of-range', gte: 0, lte: 23 }, expects: [], partName: 'hour', }); } }, /** * > Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59 */ minute(minute) { log('Parsing Datetime Minute: "%s"', minute?.value); if (!minute || !minute.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'minute' }], partName: 'minute', }); } if (!minute.match(/^[0-9]+$/)) { return minute.unmatched({ reason: 'unexpected-token', expects: [], partName: 'minute', }); } if (minute.length !== 2) { return minute.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'minute', }); } const _minute = minute.toNumber(); if (!(0 <= _minute && _minute <= 59)) { return minute.unmatched({ reason: { type: 'out-of-range', gte: 0, lte: 59 }, expects: [], partName: 'minute', }); } }, /** * > Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59 */ second(second) { log('Parsing Datetime Second: "%s"', second?.value); if (!second || !second.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'second' }], partName: 'second', }); } if (!second.match(/^[0-9]+$/)) { return second.unmatched({ reason: 'unexpected-token', expects: [], partName: 'second', }); } if (second.length !== 2) { return second.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'second', }); } const _second = second.toNumber(); if (!(0 <= _second && _second <= 59)) { return second.unmatched({ reason: { type: 'out-of-range', gte: 0, lte: 59 }, expects: [], partName: 'second', }); } }, /** * > One, two, or three ASCII digits, representing the fractional part of second */ secondFractionalPart(secondFP) { log('Parsing Datetime Second Fractional Part: "%s"', secondFP?.value); if (!secondFP || !secondFP.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'fractional part' }], partName: 'fractional part', }); } if (!secondFP.match(/^[0-9]+$/)) { return secondFP.unmatched({ reason: 'unexpected-token', expects: [], partName: 'fractional part', }); } if (!(1 <= secondFP.length && secondFP.length <= 3)) { return secondFP.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 1, lte: 3 }, expects: [], partName: 'fractional part', }); } }, /** * > Two ASCII digits, representing the week week, in the range 1 ≤ week ≤ maxweek, where maxweek is the week number of the last day of week-year year */ week(week) { log('Parsing Datetime Week: "%s"', week?.value); if (!week || !week.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'week' }], partName: 'week', }); } if (!week.match(/^[0-9]+$/)) { return week.unmatched({ reason: 'unexpected-token', expects: [], partName: 'week', }); } if (week.length !== 2) { return week.unmatched({ reason: { type: 'out-of-range-length-digit', gte: 2, lte: 2 }, expects: [], partName: 'week', }); } const maxweek = getMaxWeekNum(this._year || 0); const _week = week.toNumber(); if (!(1 <= _week && _week <= maxweek)) { return week.unmatched({ reason: { type: 'out-of-range', gte: 1, lte: maxweek }, expects: [], partName: 'date', }); } }, /** * > A U+002D HYPHEN-MINUS character (-) */ hyphen(hyphen) { log('Parsing Datetime hyphen: "%s"', hyphen?.value); if (!hyphen || !hyphen.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'hyphen' }], partName: 'datetime', }); } if (!hyphen.match('-')) { return hyphen.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'hyphen' }], partName: 'datetime', }); } }, /** * > A U+003A COLON character (:) */ coron(coron) { log('Parsing Datetime coron: "%s"', coron?.value); if (!coron || !coron.value) { return unmatched('', 'missing-token', { expects: [{ type: 'common', value: 'coron' }], partName: 'time', }); } if (!coron.match(':')) { return coron.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'coron' }], partName: 'time', }); } }, /** * > A U+003A COLON character (:) * or * End of token */ coronOrEnd(coron) { if (!coron || !coron.value) { return matched(); } if (!coron.match(':')) { return coron.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'coron' }], partName: 'time', }); } }, /** * > A U+002E FULL STOP character (.) * or * End of token */ decimalPointOrEnd(dot) { if (!dot || !dot.value) { return matched(); } if (!dot.match('.')) { return dot.unmatched({ reason: 'unexpected-token', expects: [{ type: 'common', value: 'decimal point' }], partName: 'second', }); } }, /** * > A U+0054 LATIN CAPITAL LETTER T character (T) or a U+0020 SPACE character */ localDateTimeSeparator(sep) { log('Parsing Datetime Local-Date-Time separator: "%s"', sep?.value); if (!sep || !sep.value) { return unmatched('', 'missing-token', { expects: [ { type: 'const', value: 'T' }, { type: 'common', value: 'space' }, ], }); } if (!sep.match(['T', ' '])) { return sep.unmatched({ reason: 'unexpected-token', expects: [ { type: 'const', value: 'T' }, { type: 'common', value: 'space' }, ], }); } }, /** * > A U+0054 LATIN CAPITAL LETTER T character (T) */ normalizedlocalDateTimeSeparator(sep) { log('Parsing Datetime Normalized-Local-Date-Time separator: %s', sep?.value); if (!sep || !sep.value) { return unmatched('', 'missing-token', { expects: [{ type: 'const', value: 'T' }], }); } if (!sep.match('T')) { return sep.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'T' }], }); } }, /** * > Either a U+002B PLUS SIGN character (+) or, * > if the time-zone offset is not zero, * > a U+002D HYPHEN-MINUS character (-), * > representing the sign of the time-zone offset */ plusOrMinusSign(coron) { if (!coron) { return unmatched('', 'missing-token', { expects: [ { type: 'const', value: '+' }, { type: 'const', value: '-' }, ], partName: 'time-zone', }); } if (!coron.match(['+', '-'])) { return coron.unmatched({ reason: 'unexpected-token', expects: [ { type: 'const', value: '+' }, { type: 'const', value: '-' }, ], partName: 'time-zone', }); } }, /** * > A U+0057 LATIN CAPITAL LETTER W character (W) */ weekSign(weekSign) { log('Parsing Datetime W sign: "%s"', weekSign?.value); if (!weekSign || !weekSign.value) { return unmatched('', 'missing-token', { expects: [{ type: 'const', value: 'W' }], partName: 'time-zone', }); } if (!weekSign.match('W')) { return weekSign.unmatched({ reason: 'unexpected-token', expects: [{ type: 'const', value: 'W' }], partName: 'time-zone', }); } }, /** * Extra token */ extra(extra) { log('Parsing Datetime EXTRA STRING: "%s"', extra?.value); if (extra && extra.value) { return extra.unmatched({ reason: 'extra-token', }); } }, }; const daysOfMonth = [ 0, // 1 31, // 2 28, // 3 31, // 4 30, // 5 31, // 6 30, // 7 31, // 8 31, // 9 30, // 10 31, // 11 30, // 12 31, ]; export function getMaxWeekNum(year: number) { let date = 31; while (date) { const d = new Date(Date.UTC(year, 11, date, 0, 0, 0, 0)); d.setDate(d.getDate() + 4 - (d.getDay() || 7)); const yearStart = new Date(d.getFullYear(), 0, 1); const weekNo = Math.ceil(((d.valueOf() - yearStart.valueOf()) / 86400000 + 1) / 7); if (weekNo !== 1) { return weekNo; } date--; } return NaN; }
the_stack
import { expect } from 'chai' import { concatBuffers } from '../src' import { deserializeHeaderV1Factory } from '../src/deserialize_header_v1' import { decodeEncryptionContextFactory } from '../src/decode_encryption_context' import { deserializeEncryptedDataKeysFactory } from '../src/deserialize_encrypted_data_keys' import * as fixtures from './fixtures' import { EncryptedDataKey, WebCryptoAlgorithmSuite, } from '@aws-crypto/material-management' const toUtf8 = (input: Uint8Array) => Buffer.from(input).toString() const decodeEncryptionContext = decodeEncryptionContextFactory(toUtf8) const deserializeEncryptedDataKeys = deserializeEncryptedDataKeysFactory(toUtf8) describe('deserializeFactory:deserializeMessageHeader', () => { it('return header information with context', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const basicMessageHeader = fixtures.basicMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers(basicMessageHeader, headerIv, headerAuthTag) const test = deserializeMessageHeader(buffer) if (!test) throw new Error('fail') expect(test) .to.have.property('headerLength') .and.to.deep.equal(basicMessageHeader.byteLength) expect(test) .to.have.property('rawHeader') .and.to.deep.equal(basicMessageHeader) expect(test).to.have.property('headerAuth') expect(test.headerAuth) .to.have.property('headerIv') .and.to.deep.equal(headerIv) expect(test.headerAuth) .to.have.property('headerAuthTag') .and.to.deep.equal(headerAuthTag) expect(test) .to.have.property('algorithmSuite') .and.to.be.instanceOf(WebCryptoAlgorithmSuite) expect(test.algorithmSuite.id).to.eql(0x0014) const { messageHeader } = test expect(messageHeader).to.have.property('version').and.to.eql(1) expect(messageHeader).to.have.property('type').and.to.eql(128) expect(messageHeader).to.have.property('suiteId').and.to.eql(0x0014) expect(messageHeader) .to.have.property('messageId') .and.to.deep.equal(new Uint8Array(16).fill(3)) expect(messageHeader) .to.have.property('encryptionContext') .and.to.deep.equal({ some: 'public', information: '½ + ¼ = ¾' }) expect(messageHeader) .to.have.property('encryptedDataKeys') .and.to.be.an('Array') .and.to.have.lengthOf(2) const { encryptedDataKeys } = messageHeader expect(encryptedDataKeys[0]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[0].providerInfo).to.eql('firstKey') expect(encryptedDataKeys[0].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[0].encryptedDataKey).to.deep.equal( new Uint8Array([1, 2, 3, 4, 5]) ) expect(encryptedDataKeys[1]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[1].providerInfo).to.eql('secondKey') expect(encryptedDataKeys[1].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[1].encryptedDataKey).to.deep.equal( new Uint8Array([6, 7, 8, 9, 0]) ) expect(messageHeader).to.have.property('contentType').and.to.eql(2) expect(messageHeader).to.have.property('headerIvLength').and.to.eql(12) expect(messageHeader).to.have.property('frameLength').and.to.eql(4096) }) it(`Check for early return (Postcondition): Not Enough Data. Need to have at least 22 bytes of data to begin parsing. Check for early return (Postcondition): Not Enough Data. Need to have all of the context in bytes before we can parse the next section. Check for early return (Postcondition): Not Enough Data. deserializeEncryptedDataKeys will return false if it does not have enough data. Check for early return (Postcondition): Not Enough Data. Need to have the remaining fixed length data to parse. `, () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const basicMessageHeader = fixtures.basicMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers(basicMessageHeader, headerIv, headerAuthTag) // By testing every buffer size, we check every boundary condition for "not enough data" for (let i = 0; buffer.byteLength > i; i++) { const test = deserializeMessageHeader(buffer.slice(0, i)) expect(test).to.eql(false) } }) it('return header information without context', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const zeroByteEncryptionContextMessageHeader = fixtures.zeroByteEncryptionContextMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers( zeroByteEncryptionContextMessageHeader, headerIv, headerAuthTag ) const test = deserializeMessageHeader(buffer) if (!test) throw new Error('fail') expect(test) .to.have.property('headerLength') .and.to.deep.equal(zeroByteEncryptionContextMessageHeader.byteLength) expect(test) .to.have.property('rawHeader') .and.to.deep.equal(zeroByteEncryptionContextMessageHeader) expect(test).to.have.property('headerAuth') expect(test.headerAuth) .to.have.property('headerIv') .and.to.deep.equal(headerIv) expect(test.headerAuth) .to.have.property('headerAuthTag') .and.to.deep.equal(headerAuthTag) expect(test) .to.have.property('algorithmSuite') .and.to.be.instanceOf(WebCryptoAlgorithmSuite) expect(test.algorithmSuite.id).to.eql(0x0014) const { messageHeader } = test expect(messageHeader).to.have.property('version').and.to.eql(1) expect(messageHeader).to.have.property('type').and.to.eql(128) expect(messageHeader).to.have.property('suiteId').and.to.eql(0x0014) expect(messageHeader) .to.have.property('messageId') .and.to.deep.equal(new Uint8Array(16).fill(3)) expect(messageHeader) .to.have.property('encryptionContext') .and.to.deep.equal({}) expect(messageHeader) .to.have.property('encryptedDataKeys') .and.to.be.an('Array') .and.to.have.lengthOf(2) const { encryptedDataKeys } = messageHeader expect(encryptedDataKeys[0]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[0].providerInfo).to.eql('firstKey') expect(encryptedDataKeys[0].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[0].encryptedDataKey).to.deep.equal( new Uint8Array([1, 2, 3, 4, 5]) ) expect(encryptedDataKeys[1]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[1].providerInfo).to.eql('secondKey') expect(encryptedDataKeys[1].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[1].encryptedDataKey).to.deep.equal( new Uint8Array([6, 7, 8, 9, 0]) ) expect(messageHeader).to.have.property('contentType').and.to.eql(2) expect(messageHeader).to.have.property('headerIvLength').and.to.eql(12) expect(messageHeader).to.have.property('frameLength').and.to.eql(4096) }) it('Header without context should stream correctly i.e not return data when not enough is given.', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const zeroByteEncryptionContextMessageHeader = fixtures.zeroByteEncryptionContextMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers( zeroByteEncryptionContextMessageHeader, headerIv, headerAuthTag ) for (let i = 0; buffer.byteLength > i; i++) { const test = deserializeMessageHeader(buffer.slice(0, i)) expect(test).to.eql(false) } }) it('ArrayBuffer for a Uint8Array or Buffer may be larger than the Uint8Array or Buffer that it is a view over is.', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const basicMessageHeader = fixtures.basicMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) /* Create a Uint8Array that has an a valid FrameHeader but is proceeded by "invalid" bytes. */ const buffer = concatBuffers( new Uint8Array(5), basicMessageHeader, headerIv, headerAuthTag ) expect(() => deserializeMessageHeader(buffer)).to.throw() /* Given this I can use this to construct a new view of part of the * ArrayBuffer to simulate a large ArrayBuffer that is sliced * into parts for efficiency. */ const sharingArrayBuffer = new Uint8Array( buffer.buffer, 5, buffer.byteLength - 5 ) const test = deserializeMessageHeader(sharingArrayBuffer) if (!test) throw new Error('fail') expect(test) .to.have.property('headerLength') .and.to.deep.equal(basicMessageHeader.byteLength) expect(test) .to.have.property('rawHeader') .and.to.deep.equal(basicMessageHeader) expect(test).to.have.property('headerAuth') expect(test.headerAuth) .to.have.property('headerIv') .and.to.deep.equal(headerIv) expect(test.headerAuth) .to.have.property('headerAuthTag') .and.to.deep.equal(headerAuthTag) expect(test) .to.have.property('algorithmSuite') .and.to.be.instanceOf(WebCryptoAlgorithmSuite) expect(test.algorithmSuite.id).to.eql(0x0014) const { messageHeader } = test expect(messageHeader).to.have.property('version').and.to.eql(1) expect(messageHeader).to.have.property('type').and.to.eql(128) expect(messageHeader).to.have.property('suiteId').and.to.eql(0x0014) expect(messageHeader) .to.have.property('messageId') .and.to.deep.equal(new Uint8Array(16).fill(3)) expect(messageHeader) .to.have.property('encryptionContext') .and.to.deep.equal({ some: 'public', information: '½ + ¼ = ¾' }) expect(messageHeader) .to.have.property('encryptedDataKeys') .and.to.be.an('Array') .and.to.have.lengthOf(2) const { encryptedDataKeys } = messageHeader expect(encryptedDataKeys[0]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[0].providerInfo).to.eql('firstKey') expect(encryptedDataKeys[0].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[0].encryptedDataKey).to.deep.equal( new Uint8Array([1, 2, 3, 4, 5]) ) expect(encryptedDataKeys[1]).and.to.be.instanceOf(EncryptedDataKey) expect(encryptedDataKeys[1].providerInfo).to.eql('secondKey') expect(encryptedDataKeys[1].providerId).to.eql('½ + ¼ = ¾') expect(encryptedDataKeys[1].encryptedDataKey).to.deep.equal( new Uint8Array([6, 7, 8, 9, 0]) ) expect(messageHeader).to.have.property('contentType').and.to.eql(2) expect(messageHeader).to.have.property('headerIvLength').and.to.eql(12) expect(messageHeader).to.have.property('frameLength').and.to.eql(4096) }) it('Precondition: version and type must be the required values.', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) expect(() => deserializeMessageHeader(fixtures.versionNotValidMessageHeader()) ).to.throw('Malformed Header') expect(() => deserializeMessageHeader(fixtures.typeNotValidMessageHeader()) ).to.throw('Malformed Header') expect(() => deserializeMessageHeader(fixtures.base64MessageHeader()) ).to.throw('Malformed Header: This blob may be base64 encoded.') }) it('Precondition: suiteId must be a non-committing algorithm suite.', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const suiteIdNotValidMessageHeader = fixtures.suiteIdNotValidMessageHeader() expect(() => deserializeMessageHeader(suiteIdNotValidMessageHeader) ).to.throw('Unsupported algorithm suite.') }) it('Postcondition: reservedBytes are defined as 0,0,0,0', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const reservedBytesNoZeroMessageHeader = fixtures.reservedBytesNoZeroMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers( reservedBytesNoZeroMessageHeader, headerIv, headerAuthTag ) expect(() => deserializeMessageHeader(buffer)).to.throw('Malformed Header') }) it('Postcondition: The headerIvLength must match the algorithm suite specification.', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) const reservedBytesNoZeroMessageHeader = fixtures.ivLengthMismatchMessageHeader() const headerIv = new Uint8Array(12).fill(1) const headerAuthTag = new Uint8Array(16).fill(2) const buffer = concatBuffers( reservedBytesNoZeroMessageHeader, headerIv, headerAuthTag ) expect(() => deserializeMessageHeader(buffer)).to.throw('Malformed Header') }) it('plumbs maxEncryptedDataKeys through', () => { const deserializeMessageHeader = deserializeHeaderV1Factory({ decodeEncryptionContext, deserializeEncryptedDataKeys, SdkSuite: WebCryptoAlgorithmSuite, }) expect(() => deserializeMessageHeader(fixtures.threeEdksMessagePartialHeaderV1(), { maxEncryptedDataKeys: 1, }) ).to.throw('maxEncryptedDataKeys exceeded.') }) })
the_stack
import React, { useMemo, useEffect, useState, useCallback } from 'react'; import { FormikProps } from 'formik'; import { defineMessages, FormattedMessage, MessageDescriptor, } from 'react-intl'; import { bigNumberify } from 'ethers/utils'; import moveDecimal from 'move-decimal-point'; import sortBy from 'lodash/sortBy'; import { ColonyRole, ROOT_DOMAIN_ID } from '@colony/colony-js'; import { AddressZero } from 'ethers/constants'; import EthUsd from '~core/EthUsd'; import Numeral from '~core/Numeral'; import PermissionsLabel from '~core/PermissionsLabel'; import Button from '~core/Button'; import { ItemDataType } from '~core/OmniPicker'; import { ActionDialogProps } from '~core/Dialog'; import DialogSection from '~core/Dialog/DialogSection'; import { Select, Input, Annotations, TokenSymbolSelector } from '~core/Fields'; import Heading from '~core/Heading'; import SingleUserPicker, { filterUserSelection } from '~core/SingleUserPicker'; import PermissionRequiredInfo from '~core/PermissionRequiredInfo'; import Toggle from '~core/Fields/Toggle'; import NotEnoughReputation from '~dashboard/NotEnoughReputation'; import MotionDomainSelect from '~dashboard/MotionDomainSelect'; import { Address } from '~types/index'; import HookedUserAvatar from '~users/HookedUserAvatar'; import { useLoggedInUser, useTokenBalancesForDomainsLazyQuery, AnyUser, } from '~data/index'; import { getBalanceFromToken, getTokenDecimalsWithFallback, } from '~utils/tokens'; import { useDialogActionPermissions } from '~utils/hooks/useDialogActionPermissions'; import { useTransformer } from '~utils/hooks'; import { useEnabledExtensions } from '~utils/hooks/useEnabledExtensions'; import { getUserRolesForDomain } from '../../../transformers'; import { userHasRole } from '../../../users/checks'; import { FormValues } from './CreatePaymentDialog'; import styles from './CreatePaymentDialogForm.css'; const MSG = defineMessages({ title: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.title', defaultMessage: 'Payment', }, from: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.from', defaultMessage: 'From', }, to: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.to', defaultMessage: 'Assignee', }, amount: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.amount', defaultMessage: 'Amount', }, token: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.address', defaultMessage: 'Token', }, annotation: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.annotation', defaultMessage: 'Explain why you’re making this payment (optional)', }, domainTokenAmount: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.domainTokenAmount', defaultMessage: 'Available Funds: {amount} {symbol}', }, noAmount: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.noAmount', defaultMessage: 'Amount must be greater than zero', }, noBalance: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.noBalance', defaultMessage: 'Insufficient balance in from domain pot', }, noPermissionFrom: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.noPermissionFrom', defaultMessage: `You do not have the {firstRoleRequired} and {secondRoleRequired} permissions required to take this action.`, }, noOneTxExtension: { id: 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm.noOneTxExtension', defaultMessage: `The OneTxPayment extension is not installed in this colony. Please use the Extensions Manager to install it if you want to make a new payment.`, }, userPickerPlaceholder: { id: 'SingleUserPicker.userPickerPlaceholder', defaultMessage: 'Search for a user or paste wallet address', }, }); interface Props extends ActionDialogProps { subscribedUsers: AnyUser[]; ethDomainId?: number; } const UserAvatar = HookedUserAvatar({ fetchUser: false }); const supRenderAvatar = (address: Address, item: ItemDataType<AnyUser>) => ( <UserAvatar address={address} user={item} size="xs" notSet={false} /> ); const CreatePaymentDialogForm = ({ back, colony, colony: { colonyAddress, domains, tokens }, isVotingExtensionEnabled, subscribedUsers, handleSubmit, setFieldValue, isSubmitting, isValid, values, ethDomainId: preselectedDomainId, }: Props & FormikProps<FormValues>) => { const selectedDomain = preselectedDomainId === 0 || preselectedDomainId === undefined ? ROOT_DOMAIN_ID : preselectedDomainId; const domainId = values.domainId ? parseInt(values.domainId, 10) : selectedDomain; /* * Custom error state tracking */ const [customAmountError, setCustomAmountError] = useState< MessageDescriptor | string | undefined >(undefined); const [currentFromDomain, setCurrentFromDomain] = useState<number>(domainId); const { tokenAddress, amount } = values; const selectedToken = useMemo( () => tokens.find((token) => token.address === values.tokenAddress), [tokens, values.tokenAddress], ); const { walletAddress } = useLoggedInUser(); const fromDomainRoles = useTransformer(getUserRolesForDomain, [ colony, walletAddress, domainId, ]); const domainOptions = useMemo( () => sortBy( domains.map(({ name, ethDomainId }) => ({ value: ethDomainId.toString(), label: name, })), ['value'], ), [domains], ); const [ loadTokenBalances, { data: tokenBalancesData }, ] = useTokenBalancesForDomainsLazyQuery(); useEffect(() => { if (tokenAddress) { loadTokenBalances({ variables: { colonyAddress, tokenAddresses: [tokenAddress], domainIds: [domainId], }, }); } }, [colonyAddress, tokenAddress, domainId, loadTokenBalances]); const fromDomainTokenBalance = useMemo(() => { const token = tokenBalancesData && tokenBalancesData.tokens.find(({ address }) => address === tokenAddress); if (token) { /* * Reset our custom error state, since we changed the domain */ setCustomAmountError(undefined); return getBalanceFromToken(token, domainId); } return null; }, [domainId, tokenAddress, tokenBalancesData]); useEffect(() => { if (selectedToken && amount) { const convertedAmount = bigNumberify( moveDecimal( amount, getTokenDecimalsWithFallback(selectedToken.decimals), ), ); if ( fromDomainTokenBalance && (fromDomainTokenBalance.lt(convertedAmount) || fromDomainTokenBalance.isZero()) ) { /* * @NOTE On custom, parallel, in-component error handling * * We need to keep track of a separate error state, since we are doing * custom validation (checking if a domain has enough funds), alongside * using a validationSchema. * * This makes it so that even if we manual set the error, it will get * overwritten instantly when the next Formik State update triggers, making * it basically impossible for us to manually put the Form into an error * state. * * See: https://github.com/formium/formik/issues/706 * * Because of this, we keep our own error state that runs in parallel * to Formik's error state. */ setCustomAmountError(MSG.noBalance); } else { setCustomAmountError(undefined); } } }, [ amount, domainId, fromDomainRoles, fromDomainTokenBalance, selectedToken, setCustomAmountError, ]); const userHasFundingPermission = userHasRole( fromDomainRoles, ColonyRole.Funding, ); const userHasAdministrationPermission = userHasRole( fromDomainRoles, ColonyRole.Administration, ); const hasRoles = userHasFundingPermission && userHasAdministrationPermission; const requiredRoles: ColonyRole[] = [ ColonyRole.Funding, ColonyRole.Administration, ]; const [userHasPermission, onlyForceAction] = useDialogActionPermissions( colony.colonyAddress, hasRoles, isVotingExtensionEnabled, values.forceAction, domainId, ); const { isOneTxPaymentExtensionEnabled } = useEnabledExtensions({ colonyAddress, }); const handleFromDomainChange = useCallback( (fromDomainValue) => { const fromDomainId = parseInt(fromDomainValue, 10); const selectedMotionDomainId = parseInt(values.motionDomainId, 10); if ( fromDomainId !== ROOT_DOMAIN_ID && fromDomainId !== currentFromDomain ) { setCurrentFromDomain(fromDomainId); } else { setCurrentFromDomain(ROOT_DOMAIN_ID); } if ( selectedMotionDomainId !== ROOT_DOMAIN_ID && selectedMotionDomainId !== fromDomainId ) { setFieldValue('motionDomainId', fromDomainId); } }, [currentFromDomain, setFieldValue, values.motionDomainId], ); const handleFilterMotionDomains = useCallback( (optionDomain) => { const optionDomainId = parseInt(optionDomain.value, 10); if (currentFromDomain === ROOT_DOMAIN_ID) { return optionDomainId === ROOT_DOMAIN_ID; } return ( optionDomainId === currentFromDomain || optionDomainId === ROOT_DOMAIN_ID ); }, [currentFromDomain], ); const handleMotionDomainChange = useCallback( (motionDomainId) => setFieldValue('motionDomainId', motionDomainId), [setFieldValue], ); const canMakePayment = userHasPermission && isOneTxPaymentExtensionEnabled; const inputDisabled = !canMakePayment || onlyForceAction; return ( <> <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.modalHeading}> {isVotingExtensionEnabled && ( <div className={styles.motionVoteDomain}> <MotionDomainSelect colony={colony} onDomainChange={handleMotionDomainChange} disabled={values.forceAction} /* * @NOTE We can only create a motion to vote in a subdomain if we * create a payment from that subdomain */ filterDomains={handleFilterMotionDomains} initialSelectedDomain={domainId} /> </div> )} <div className={styles.headingContainer}> <Heading appearance={{ size: 'medium', margin: 'none', theme: 'dark' }} text={MSG.title} /> {hasRoles && isVotingExtensionEnabled && ( <Toggle label={{ id: 'label.force' }} name="forceAction" disabled={!canMakePayment} /> )} </div> </div> </DialogSection> {!userHasPermission && ( <DialogSection> <PermissionRequiredInfo requiredRoles={requiredRoles} /> </DialogSection> )} <DialogSection> <div className={styles.domainSelects}> <div> <Select options={domainOptions} label={MSG.from} name="domainId" appearance={{ theme: 'grey', width: 'fluid' }} onChange={handleFromDomainChange} /> {!!tokenAddress && ( <div className={styles.domainPotBalance}> <FormattedMessage {...MSG.domainTokenAmount} values={{ amount: ( <Numeral appearance={{ size: 'small', theme: 'grey', }} value={fromDomainTokenBalance || 0} unit={getTokenDecimalsWithFallback( selectedToken && selectedToken.decimals, )} truncate={3} /> ), symbol: (selectedToken && selectedToken.symbol) || '???', }} /> </div> )} </div> </div> </DialogSection> <DialogSection> <div className={styles.singleUserContainer}> <SingleUserPicker appearance={{ width: 'wide' }} data={subscribedUsers} label={MSG.to} name="recipient" filter={filterUserSelection} renderAvatar={supRenderAvatar} disabled={inputDisabled} placeholder={MSG.userPickerPlaceholder} /> </div> </DialogSection> <DialogSection> <div className={styles.tokenAmount}> <div className={styles.tokenAmountInputContainer}> <Input label={MSG.amount} name="amount" appearance={{ theme: 'minimal', align: 'right', }} formattingOptions={{ delimiter: ',', numeral: true, numeralDecimalScale: getTokenDecimalsWithFallback( selectedToken && selectedToken.decimals, ), }} disabled={inputDisabled} /* * Force the input component into an error state * This is needed for our custom error state to work */ forcedFieldError={customAmountError} /> </div> <div className={styles.tokenAmountSelect}> <TokenSymbolSelector label={MSG.token} tokens={tokens} name="tokenAddress" elementOnly appearance={{ alignOptions: 'right', theme: 'grey' }} disabled={inputDisabled} /> </div> {values.tokenAddress === AddressZero && ( <div className={styles.tokenAmountUsd}> <EthUsd appearance={{ theme: 'grey', size: 'small' }} value={ /* * @NOTE Set value to 0 if amount is only the decimal point * Just entering the decimal point will pass it through to EthUsd * and that will try to fetch the balance for, which, obviously, will fail */ values.amount && values.amount !== '.' ? values.amount : '0' } /> </div> )} </div> </DialogSection> <DialogSection> <Annotations label={MSG.annotation} name="annotation" disabled={inputDisabled} /> </DialogSection> {!userHasPermission && ( <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.noPermissionFromMessage}> <FormattedMessage {...MSG.noPermissionFrom} values={{ firstRoleRequired: ( <PermissionsLabel permission={ColonyRole.Funding} name={{ id: `role.${ColonyRole.Funding}` }} /> ), secondRoleRequired: ( <PermissionsLabel permission={ColonyRole.Administration} name={{ id: `role.${ColonyRole.Administration}` }} /> ), }} /> </div> </DialogSection> )} {userHasPermission && !isOneTxPaymentExtensionEnabled && ( <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.noPermissionFromMessage}> <FormattedMessage {...MSG.noOneTxExtension} /> </div> </DialogSection> )} {onlyForceAction && ( <NotEnoughReputation appearance={{ marginTop: 'negative' }} domainId={domainId} /> )} <DialogSection appearance={{ align: 'right', theme: 'footer' }}> <Button appearance={{ theme: 'secondary', size: 'large' }} onClick={back} text={{ id: 'button.back' }} /> <Button appearance={{ theme: 'primary', size: 'large' }} onClick={() => handleSubmit()} text={{ id: 'button.confirm' }} loading={isSubmitting} /* * Disable Form submissions if either the form is invalid, or * if our custom state was triggered. */ disabled={!isValid || !!customAmountError || inputDisabled} style={{ width: styles.wideButton }} /> </DialogSection> </> ); }; CreatePaymentDialogForm.displayName = 'dashboard.CreatePaymentDialog.CreatePaymentDialogForm'; export default CreatePaymentDialogForm;
the_stack
import {act, fireEvent, render} from '@testing-library/react'; import {installMouseEvent} from '@react-spectrum/test-utils'; import {press, testKeypresses} from './utils'; import {Provider} from '@adobe/react-spectrum'; import React, {useState} from 'react'; import {Slider} from '../'; import {theme} from '@react-spectrum/theme-default'; import userEvent from '@testing-library/user-event'; describe('Slider', function () { it('supports aria-label', function () { let {getByRole} = render(<Slider aria-label="The Label" />); let group = getByRole('group'); expect(group).toHaveAttribute('aria-label', 'The Label'); // No label/value expect(group.textContent).toBeFalsy(); let slider = getByRole('slider'); expect(slider).toHaveAttribute('aria-valuetext', '0'); }); it('supports label', function () { let {getByRole} = render(<Slider label="The Label" />); let group = getByRole('group'); let labelId = group.getAttribute('aria-labelledby'); let slider = getByRole('slider'); expect(slider.getAttribute('aria-labelledby')).toBe(labelId); expect(slider).toHaveAttribute('aria-valuetext', '0'); let label = document.getElementById(labelId); expect(label).toHaveTextContent(/^The Label$/); // https://bugs.webkit.org/show_bug.cgi?id=172464 // expect(label).toHaveAttribute('for', getByRole('slider').id); expect(label).not.toHaveAttribute('for'); // Shows value as well let output = getByRole('status'); expect(output).toHaveTextContent('0'); expect(output).toHaveAttribute('for', getByRole('slider').id); expect(output).not.toHaveAttribute('aria-labelledby'); expect(output).toHaveAttribute('aria-live', 'off'); }); it('supports showValueLabel: false', function () { let {getByRole, queryByRole} = render(<Slider label="The Label" showValueLabel={false} />); let group = getByRole('group'); expect(group.textContent).toBe('The Label'); let slider = getByRole('slider'); expect(slider).toHaveAttribute('aria-valuetext', '0'); expect(queryByRole('status')).toBeNull(); }); it('supports disabled', function () { let {getByRole, getAllByRole} = render(<div> <button>A</button> <Slider label="The Label" defaultValue={20} isDisabled /> <button>B</button> </div>); let slider = getByRole('slider'); let [buttonA, buttonB] = getAllByRole('button'); expect(slider).toBeDisabled(); userEvent.tab(); expect(document.activeElement).toBe(buttonA); userEvent.tab(); expect(document.activeElement).toBe(buttonB); }); it('can be focused', function () { let {getByRole, getAllByRole} = render(<div> <button>A</button> <Slider label="The Label" defaultValue={20} /> <button>B</button> </div>); let slider = getByRole('slider'); let [buttonA, buttonB] = getAllByRole('button'); act(() => { slider.focus(); }); expect(document.activeElement).toBe(slider); userEvent.tab(); expect(document.activeElement).toBe(buttonB); userEvent.tab({shift: true}); userEvent.tab({shift: true}); expect(document.activeElement).toBe(buttonA); }); it('supports defaultValue', function () { let {getByRole} = render(<Slider label="The Label" defaultValue={20} />); let slider = getByRole('slider'); let output = getByRole('status'); expect(slider).toHaveProperty('value', '20'); expect(slider).toHaveAttribute('aria-valuetext', '20'); expect(output).toHaveTextContent('20'); fireEvent.change(slider, {target: {value: '40'}}); expect(slider).toHaveProperty('value', '40'); expect(slider).toHaveAttribute('aria-valuetext', '40'); expect(output).toHaveTextContent('40'); }); it('can be controlled', function () { let renders = []; function Test() { let [value, setValue] = useState(50); renders.push(value); return (<Slider label="The Label" value={value} onChange={setValue} />); } let {getByRole} = render(<Test />); let output = getByRole('status'); let slider = getByRole('slider'); expect(slider).toHaveProperty('value', '50'); expect(slider).toHaveAttribute('aria-valuetext', '50'); expect(output).toHaveTextContent('50'); fireEvent.change(slider, {target: {value: '55'}}); expect(slider).toHaveProperty('value', '55'); expect(slider).toHaveAttribute('aria-valuetext', '55'); expect(output).toHaveTextContent('55'); expect(renders).toStrictEqual([50, 55]); }); it('supports a custom getValueLabel', function () { function Test() { let [value, setValue] = useState(50); return (<Slider label="The Label" value={value} onChange={setValue} getValueLabel={value => `A${value}B`} />); } let {getByRole} = render(<Test />); let output = getByRole('status'); let slider = getByRole('slider'); expect(output).toHaveTextContent('A50B'); // TODO should aria-valuetext be formatted as well? expect(slider).toHaveAttribute('aria-valuetext', '50'); fireEvent.change(slider, {target: {value: '55'}}); expect(output).toHaveTextContent('A55B'); expect(slider).toHaveAttribute('aria-valuetext', '55'); }); describe('formatOptions', () => { it('prefixes the value with a plus sign if needed', function () { let {getByRole} = render( <Slider label="The Label" minValue={-50} maxValue={50} defaultValue={10} /> ); let output = getByRole('status'); let slider = getByRole('slider'); expect(output).toHaveTextContent('+10'); expect(slider).toHaveAttribute('aria-valuetext', '+10'); fireEvent.change(slider, {target: {value: '0'}}); expect(output).toHaveTextContent('0'); expect(slider).toHaveAttribute('aria-valuetext', '0'); }); it('supports setting custom formatOptions', function () { let {getByRole} = render( <Slider label="The Label" minValue={0} maxValue={1} step={0.01} defaultValue={0.2} formatOptions={{style: 'percent'}} /> ); let output = getByRole('status'); let slider = getByRole('slider'); expect(output).toHaveTextContent('20%'); expect(slider).toHaveAttribute('aria-valuetext', '20%'); fireEvent.change(slider, {target: {value: 0.5}}); expect(output).toHaveTextContent('50%'); expect(slider).toHaveAttribute('aria-valuetext', '50%'); }); }); describe('keyboard interactions', () => { // Can't test arrow/page up/down, home/end arrows because they are handled by the browser and JSDOM doesn't feel like it. it.each` Name | props | commands ${'(left/right arrows, ltr)'} | ${{locale: 'de-DE'}} | ${[{left: press.ArrowRight, result: +1}, {left: press.ArrowLeft, result: -1}]} ${'(left/right arrows, rtl)'} | ${{locale: 'ar-AE'}} | ${[{left: press.ArrowRight, result: -1}, {left: press.ArrowLeft, result: +1}]} ${'(left/right arrows, isDisabled)'} | ${{locale: 'de-DE', isDisabled: true}}| ${[{left: press.ArrowRight, result: 0}, {left: press.ArrowLeft, result: 0}]} `('$Name moves the slider in the correct direction', function ({props, commands}) { let tree = render( <Provider theme={theme} {...props}> <Slider label="Label" defaultValue={50} minValue={0} maxValue={100} /> </Provider> ); let slider = tree.getByRole('slider'); testKeypresses([slider, slider], commands); }); it.each` Name | props | commands ${'(left/right arrows, ltr)'} | ${{locale: 'de-DE'}} | ${[{left: press.ArrowRight, result: +10}, {left: press.ArrowLeft, result: -10}]} ${'(left/right arrows, rtl)'} | ${{locale: 'ar-AE'}} | ${[{left: press.ArrowRight, result: -10}, {left: press.ArrowLeft, result: +10}]} `('$Name respects the step size', function ({props, commands}) { let tree = render( <Provider theme={theme} {...props}> <Slider label="Label" step={10} defaultValue={50} /> </Provider> ); let slider = tree.getByRole('slider'); testKeypresses([slider, slider], commands); }); it.each` Name | props | commands ${'(left/right arrows, ltr)'} | ${{locale: 'de-DE'}} | ${[{left: press.ArrowLeft, result: -1}, {left: press.ArrowLeft, result: 0}]} ${'(left/right arrows, rtl)'} | ${{locale: 'ar-AE'}} | ${[{left: press.ArrowRight, result: -1}, {left: press.ArrowRight, result: 0}]} `('$Name is clamped by min/max', function ({props, commands}) { let tree = render( <Provider theme={theme} {...props}> <Slider label="Label" minValue={-1} defaultValue={0} maxValue={1} /> </Provider> ); let slider = tree.getByRole('slider'); testKeypresses([slider, slider], commands); }); }); describe('mouse interactions', () => { beforeAll(() => { jest.spyOn(window.HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => 100); }); afterAll(() => { // @ts-ignore window.HTMLElement.prototype.offsetWidth.mockReset(); }); installMouseEvent(); it('can click and drag handle', () => { let onChangeSpy = jest.fn(); let {getByRole} = render( <Slider label="The Label" onChange={onChangeSpy} defaultValue={50} /> ); let slider = getByRole('slider'); let thumb = slider.parentElement; fireEvent.mouseDown(thumb, {clientX: 50, pageX: 50}); expect(onChangeSpy).not.toHaveBeenCalled(); expect(document.activeElement).toBe(slider); fireEvent.mouseMove(thumb, {pageX: 10}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy).toHaveBeenLastCalledWith(10); fireEvent.mouseMove(thumb, {pageX: -10}); expect(onChangeSpy).toHaveBeenCalledTimes(2); expect(onChangeSpy).toHaveBeenLastCalledWith(0); fireEvent.mouseMove(thumb, {pageX: 120}); expect(onChangeSpy).toHaveBeenCalledTimes(3); expect(onChangeSpy).toHaveBeenLastCalledWith(100); fireEvent.mouseUp(thumb, {pageX: 120}); expect(onChangeSpy).toHaveBeenCalledTimes(3); }); it('cannot click and drag handle when disabled', () => { let onChangeSpy = jest.fn(); let {getByRole} = render( <Slider label="The Label" onChange={onChangeSpy} defaultValue={50} isDisabled /> ); let slider = getByRole('slider'); let thumb = slider.parentElement; fireEvent.mouseDown(thumb, {clientX: 50, pageX: 50}); expect(onChangeSpy).not.toHaveBeenCalled(); expect(document.activeElement).not.toBe(slider); fireEvent.mouseMove(thumb, {pageX: 10}); expect(onChangeSpy).not.toHaveBeenCalled(); fireEvent.mouseUp(thumb, {pageX: 10}); expect(onChangeSpy).not.toHaveBeenCalled(); }); it('can click on track to move handle', () => { let onChangeSpy = jest.fn(); let {getByRole} = render( <Slider label="The Label" onChange={onChangeSpy} defaultValue={50} /> ); let slider = getByRole('slider'); let thumb = slider.parentElement.parentElement; // @ts-ignore let [leftTrack, rightTrack] = [...thumb.parentElement.children].filter(c => c !== thumb); // left track fireEvent.mouseDown(leftTrack, {clientX: 20, pageX: 20}); expect(document.activeElement).toBe(slider); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy).toHaveBeenLastCalledWith(20); fireEvent.mouseUp(thumb, {pageX: 20}); expect(onChangeSpy).toHaveBeenCalledTimes(1); // right track onChangeSpy.mockClear(); fireEvent.mouseDown(rightTrack, {clientX: 70, pageX: 70}); expect(document.activeElement).toBe(slider); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy).toHaveBeenLastCalledWith(70); fireEvent.mouseUp(thumb, {pageX: 70}); expect(onChangeSpy).toHaveBeenCalledTimes(1); }); it('cannot click on track to move handle when disabled', () => { let onChangeSpy = jest.fn(); let {getByRole} = render( <Slider label="The Label" onChange={onChangeSpy} defaultValue={50} isDisabled /> ); let slider = getByRole('slider'); let thumb = slider.parentElement.parentElement; // @ts-ignore let [leftTrack, rightTrack] = [...thumb.parentElement.children].filter(c => c !== thumb); // left track fireEvent.mouseDown(leftTrack, {clientX: 20, pageX: 20}); expect(document.activeElement).not.toBe(slider); expect(onChangeSpy).not.toHaveBeenCalled(); fireEvent.mouseUp(thumb, {pageX: 20}); expect(onChangeSpy).not.toHaveBeenCalled(); // right track onChangeSpy.mockClear(); fireEvent.mouseDown(rightTrack, {clientX: 70, pageX: 70}); expect(document.activeElement).not.toBe(slider); expect(onChangeSpy).not.toHaveBeenCalled(); fireEvent.mouseUp(thumb, {pageX: 70}); expect(onChangeSpy).not.toHaveBeenCalled(); }); it('clicking on the label should focus the first thumb', () => { let {getByText, getByRole} = render( <Slider label="The Label" /> ); let label = getByText('The Label'); let thumb = getByRole('slider'); fireEvent.click(label); expect(document.activeElement).toBe(thumb); }); }); describe('touch interactions', () => { beforeAll(() => { jest.spyOn(window.HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => 100); }); afterAll(() => { // @ts-ignore window.HTMLElement.prototype.offsetWidth.mockReset(); }); it('doesn\'t jump to second touch on track while already dragging', () => { let onChangeSpy = jest.fn(); let {getByRole} = render( <Slider label="The Label" onChange={onChangeSpy} defaultValue={50} /> ); let slider = getByRole('slider'); let thumb = slider.parentElement.parentElement; // @ts-ignore let [, rightTrack] = [...thumb.parentElement.children].filter(c => c !== thumb); fireEvent.touchStart(thumb, {changedTouches: [{identifier: 1, clientX: 50, pageX: 50}]}); expect(onChangeSpy).toHaveBeenCalledTimes(0); fireEvent.touchStart(rightTrack, {changedTouches: [{identifier: 2, clientX: 60, pageX: 60}]}); fireEvent.touchMove(rightTrack, {changedTouches: [{identifier: 2, clientX: 70, pageX: 70}]}); fireEvent.touchEnd(rightTrack, {changedTouches: [{identifier: 2, clientX: 70, pageX: 70}]}); expect(onChangeSpy).toHaveBeenCalledTimes(0); fireEvent.touchMove(thumb, {changedTouches: [{identifier: 1, clientX: 30, pageX: 30}]}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy).toHaveBeenLastCalledWith(30); fireEvent.touchEnd(thumb, {changedTouches: [{identifier: 1, clientX: 30, pageX: 30}]}); expect(onChangeSpy).toHaveBeenCalledTimes(1); }); }); });
the_stack
import React, { Component } from 'react'; import yaml from 'js-yaml'; import { ipcRenderer } from 'electron'; //IMPORT HELPER FUNCTIONS import convertYamlToState from './helpers/yamlParser'; import setD3State from './helpers/setD3State'; import parseOpenError from './helpers/parseOpenError'; import { runDockerComposeValidation } from '../common/runShellTasks'; import resolveEnvVariables from '../common/resolveEnvVariables'; // IMPORT REACT CONTAINERS OR COMPONENTS import LeftNav from './components/LeftNav'; import OptionBar from './components/OptionBar'; import D3Wrapper from './components/D3Wrapper'; import TabBar from './components/TabBar'; //IMPORT TYPES import { State, FileOpen, UpdateOption, UpdateView, SelectNetwork, SwitchTab, } from './App.d'; const initialState: State = { openFiles: [], openErrors: [], selectedContainer: '', fileOpened: false, filePath: '', services: {}, dependsOn: { name: 'placeholder', }, networks: {}, selectedNetwork: '', volumes: {}, volumesClicked: {}, bindMounts: [], bindMountsClicked: {}, view: 'depends_on', options: { ports: false, volumes: false, selectAll: false, }, version: '', }; class App extends Component<{}, State> { constructor(props: {}) { super(props); // Copy of initial state object this.state = { ...initialState }; } setSelectedContainer = (containerName: string) => { this.setState({ ...this.state, selectedContainer: containerName }); }; updateView: UpdateView = (view) => { this.setState((state) => { return { ...state, view, selectedNetwork: '', }; }); }; updateOption: UpdateOption = (option) => { const newState: State = { ...this.state, options: { ...this.state.options, [option]: !this.state.options[option] }, }; // check if toggling select all on or off if (option === 'selectAll') { if (newState.options.selectAll) { newState.options.ports = true; newState.options.volumes = true; } else { newState.options.ports = false; newState.options.volumes = false; } // check if select all should be on or off } else { if (newState.options.ports && newState.options.volumes) { newState.options.selectAll = true; } else { newState.options.selectAll = false; } } this.setState(newState); }; selectNetwork: SelectNetwork = (network) => { this.setState({ view: 'networks', selectedNetwork: network }); }; convertAndStoreYamlJSON = (yamlText: string, filePath: string) => { // Convert Yaml to state object. const yamlJSON = yaml.safeLoad(yamlText); const yamlState = convertYamlToState(yamlJSON, filePath); // Copy options and open files state const openFiles = this.state.openFiles.slice(); const { options } = this.state; // Don't add a file that is already opened to the openFiles array if (!openFiles.includes(filePath)) openFiles.push(filePath); // Set global variables for d3 simulation window.d3State = setD3State(yamlState.services); // Store opened file state in localStorage under the current state item call "state" as well as an individual item using the filePath as the key. localStorage.setItem('state', JSON.stringify(yamlState)); localStorage.setItem(`${filePath}`, JSON.stringify(yamlState)); this.setState({ ...initialState, ...yamlState, fileOpened: true, openFiles, options, }); }; /** * @param file: a File classed object * @returns void * @description validates the docker-compose file * ** if no errors, passes file string along to convert and store yaml method * ** if errors, passes error string to handle file open errors method */ fileOpen: FileOpen = (file: File) => { console.log('Opening file'); const fileReader = new FileReader(); // check for valid file path if (file.path) { /* TODO: refactor error handling */ runDockerComposeValidation(file.path).then((validationResults: any) => { if (validationResults.error) { this.handleFileOpenError(validationResults.error); } else { // event listner to run after the file has been read as text fileReader.onload = () => { // if successful read, invoke method to convert and store to state if (fileReader.result) { let yamlText = fileReader.result.toString(); //if docker-compose uses env file, replace the variables with value from env file if (validationResults.envResolutionRequired) { yamlText = resolveEnvVariables(yamlText, file.path); } this.convertAndStoreYamlJSON(yamlText, file.path); } }; // read the file fileReader.readAsText(file); } }); } }; /** * @param filePath -> string * @returns void * @description sets state to the state stored in localStorage of the file * associated with the given filePath. */ switchTab: SwitchTab = (filePath: string, openFiles?: Array<string>) => { // Extract the desired tab state from localStorage const tabState = JSON.parse(localStorage.getItem(filePath) || '{}'); // Create new state object with the returned tab state let newState; if (openFiles) newState = { ...this.state, ...tabState, openFiles, }; else newState = { ...this.state, ...tabState, }; // Set the 'state' item in localStorage to the tab state. This means that tab is the current tab, which would be used if the app got reloaded. localStorage.setItem('state', JSON.stringify(tabState)); // Set the d3 state using the services extracted from the tabState and then setState window.d3State = setD3State(newState.services); this.setState(newState); }; /** * @param filePath -> string * @returns void * @description removes the tab corresponding to the given file path */ closeTab: SwitchTab = (filePath: string) => { // Grab current open files and remove the file path of the tab to be closed, assign the // updated array to newOpenFiles const { openFiles, options } = this.state; const newOpenFiles = openFiles.filter((file) => file != filePath); // Remove the state object associated with the file path in localStorage localStorage.removeItem(filePath); // If the tab to be closed is the active tab, reset d3 and delete "state" object from local // storage and set state to the initial state with the updated open files array included. if (filePath === this.state.filePath) { // Remove the 'state' localStorage item, which represents the // services of the currently opened file. localStorage.removeItem('state'); // Stop the simulation to prevent d3 transform errors related // to 'tick' events const { simulation } = window.d3State; simulation.stop(); // If there are other open tabs, switch to the first open one // If not, reset to initialState with selected options. if (openFiles.length > 1) this.switchTab(newOpenFiles[0], newOpenFiles); else this.setState({ ...initialState, options }); } else this.setState({ ...this.state, openFiles: newOpenFiles }); }; /** * @param errorText -> string * @returns void * @description sets state with array of strings of different errors */ handleFileOpenError = (errorText: Error) => { // Stop the simulation to prevent hundreds of d3 transform errors from occuring. This is rare but its a simple fix to prevent it. const { simulation } = window.d3State; simulation.stop(); // Grab the current openFiles array so that we don't lose them when setting state. const openErrors = parseOpenError(errorText); const { openFiles } = this.state; this.setState({ ...initialState, openErrors, openFiles, fileOpened: false, }); }; componentDidMount() { if (ipcRenderer) { ipcRenderer.on('file-open-error-within-electron', (event, arg) => { this.handleFileOpenError(arg); }); ipcRenderer.on('file-opened-within-electron', (event, arg) => { this.convertAndStoreYamlJSON(arg, ''); }); } const stateJSON = localStorage.getItem('state'); if (stateJSON) { const stateJS = JSON.parse(stateJSON); // set d3 state window.d3State = setD3State(stateJS.services); //Create openFile state array from items in localStorage const openFiles = []; const keys = Object.keys(localStorage); for (let key of keys) { if (key !== 'state') { const item = localStorage.getItem(key); try { const parsed = JSON.parse(item || '{}'); openFiles.push(parsed.filePath); } catch { console.log( 'Item from localStorage not included in openFiles: ', item, ); } } } this.setState({ ...initialState, ...stateJS, openFiles, }); } } componentWillUnmount() { if (ipcRenderer) { ipcRenderer.removeAllListeners('file-opened-within-electron'); ipcRenderer.removeAllListeners('file-open-error-within-electron'); } } render() { return ( <div className="app-class"> {/* dummy div to create draggable bar at the top of application to replace removed native bar */} <div className="draggable" /> <LeftNav fileOpened={this.state.fileOpened} fileOpen={this.fileOpen} selectedContainer={this.state.selectedContainer} service={this.state.services[this.state.selectedContainer]} currentFilePath={this.state.filePath} /> <div className="main flex"> <OptionBar view={this.state.view} options={this.state.options} networks={this.state.networks} updateView={this.updateView} updateOption={this.updateOption} selectNetwork={this.selectNetwork} selectedNetwork={this.state.selectedNetwork} /> <TabBar activePath={this.state.filePath} openFiles={this.state.openFiles} switchTab={this.switchTab} closeTab={this.closeTab} /> <D3Wrapper openErrors={this.state.openErrors} fileOpened={this.state.fileOpened} fileOpen={this.fileOpen} services={this.state.services} setSelectedContainer={this.setSelectedContainer} options={this.state.options} volumes={this.state.volumes} bindMounts={this.state.bindMounts} view={this.state.view} networks={this.state.networks} selectedNetwork={this.state.selectedNetwork} /> </div> </div> ); } } export default App;
the_stack
import * as assert from 'assert'; import { v4 as uuid } from 'uuid'; import { generate as randomstring } from 'randomstring'; import * as request from 'supertest'; import * as requestPromise from 'request-promise'; import * as requestLegacy from 'request'; import * as httpstatus from 'http-status'; import * as sinon from 'sinon'; import * as express from 'express'; import * as store from '../../lib/db/store'; import * as types from '../../lib/db/db-types'; import * as dbobjects from '../../lib/db/objects'; import * as auth from '../../lib/restapi/auth'; import * as visrec from '../../lib/training/visualrecognition'; import * as trainingtypes from '../../lib/training/training-types'; import testapiserver from './testserver'; import loggerSetup from '../../lib/utils/logger'; const log = loggerSetup(); let testServer: express.Express; describe('REST API - image training for managed pool classes', () => { const userid = uuid(); const classid = randomstring({ charset: 'alphabetic', length: 30 }).toLowerCase(); let authStub: sinon.SinonStub<any, any>; let checkUserStub: sinon.SinonStub<any, any>; let requireSupervisorStub: sinon.SinonStub<any, any>; let getStub: sinon.SinonStub<[string, (requestPromise.RequestPromiseOptions | undefined)?, (requestLegacy.RequestCallback | undefined)?], requestPromise.RequestPromise>; let createStub: sinon.SinonStub<[string, (requestPromise.RequestPromiseOptions | undefined)?, (requestLegacy.RequestCallback | undefined)?], requestPromise.RequestPromise>; let deleteStub: sinon.SinonStub<[string, (requestPromise.RequestPromiseOptions | undefined)?, (requestLegacy.RequestCallback | undefined)?], requestPromise.RequestPromise>; function authNoOp( req: Express.Request, res: Express.Response, next: (err?: Error) => void) { const reqWithUser = req as auth.RequestWithUser; reqWithUser.user = { sub : userid, app_metadata : { tenant : classid, role : 'student', }, }; next(); } const firstCredsApi = '1234567890123456789012345678901234567890'; const secondCredsApi = '0123456789012345678901234567890123456789'; let failCredsId: string; let firstCredsId: string; let secondCredsId: string; let firstProject: types.Project; let secondProject: types.Project; let thirdProject: types.Project; let workspaceId: string; function setupPoolCreds() { const firstCredsSvc = 'visrec'; const firstCredsUser = undefined; const firstCredsPass = undefined; const firstCredsType = 'visrec_lite'; const firstCredsNote = 'test img creds'; const secondCredsSvc = 'visrec'; const secondCredsUser = undefined; const secondCredsPass = undefined; const secondCredsType = 'visrec_lite'; const secondCredsNote = 'additional img creds'; const firstCreds = dbobjects.createBluemixCredentialsPool(firstCredsSvc, firstCredsApi, firstCredsUser, firstCredsPass, firstCredsType); firstCreds.notes = firstCredsNote; firstCredsId = firstCreds.id; const firstCredsObj = dbobjects.getCredentialsPoolAsDbRow(firstCreds); const secondCreds = dbobjects.createBluemixCredentialsPool(secondCredsSvc, secondCredsApi, secondCredsUser, secondCredsPass, secondCredsType); secondCreds.notes = secondCredsNote; secondCredsId = secondCreds.id; const secondCredsObj = dbobjects.getCredentialsPoolAsDbRow(secondCreds); return store.storeBluemixCredentialsPool(firstCredsObj) .then(() => { return store.storeBluemixCredentialsPool(secondCredsObj); }); } function setupProjects() { const firstProjectName = 'my project'; const secondProjectName = 'my other project'; const thirdProjectName = 'my final project'; const projType = 'images'; return store.storeProject(userid, classid, projType, firstProjectName, 'en', [], false) .then((proj) => { firstProject = proj; return store.storeProject(userid, classid, projType, secondProjectName, 'en', [], false); }) .then((proj) => { secondProject = proj; return store.storeProject(userid, classid, projType, thirdProjectName, 'en', [], false); }) .then((proj) => { thirdProject = proj; }); } function setupTrainingData() { const firstLabel = 'spider'; const secondLabel = 'fly'; const data: { imageurl: string, label: string}[] = [ { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/0/04/2016.09.02.-11-Kaefertaler_Wald-Mannheim--Gartenkreuzspinne-Weibchen.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/6/6c/Wet_Spider_01_%28MK%29.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/0/08/2013.07.01-14-Wustrow-Neu_Drosedow-Erdbeerspinne-Maennchen.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/5/59/Araneus_diadematus_qtl1.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/f/f3/Araneus_diadematus_%28Clerck%2C_1757%29.JPG' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/6/67/Araneus_trifolium_and_its_web_with_fog_droplets_at_Twin_Peaks_in_San_Francisco.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/c/ca/Argiope_bruennichi_08Oct10.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/7/77/Argiope_bruennichi_QXGA.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/5/54/Argiope_lobata%2C_female._Villeveyrac_01.jpg' }, { label : firstLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/e/e2/Argiope_July_2012-3.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/e/e4/2017.07.11.-04-Lindenberg_%28Tauche%29--Barbarossa-Fliege-Maennchen.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/d/d0/2017.06.18.-20-Viernheim--Barbarossa-Fliege-Weibchen.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/5/54/2015.07.16.-16-Viernheim--Grosse_Wolfsfliege-Weibchen.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/4/40/Schwarze_Habichtsfliege_Dioctria_atricapilla.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/4/46/2015.07.16.-02-Viernheim--Barbarossa-Fliege-Maennchen.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/c/ce/2015.07.16.-01-Viernheim--Barbarossa-Fliege-Maennchen.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/f/fb/Asilidae_by_kadavoor.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/2/2b/Asilidae_2_by_kadavoor.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/d/dc/Calliphora_hilli.jpg' }, { label : secondLabel, imageurl : 'https://upload.wikimedia.org/wikipedia/commons/b/bb/Unid_Brachycera_diagonal_20070604.jpg' }, ]; return store.addLabelToProject(userid, classid, firstProject.id, firstLabel) .then(() => { return store.addLabelToProject(userid, classid, secondProject.id, firstLabel); }) .then(() => { return store.addLabelToProject(userid, classid, thirdProject.id, firstLabel); }) .then(() => { return store.addLabelToProject(userid, classid, firstProject.id, secondLabel); }) .then(() => { return store.addLabelToProject(userid, classid, secondProject.id, secondLabel); }) .then(() => { return store.addLabelToProject(userid, classid, thirdProject.id, secondLabel); }) .then(() => { return store.bulkStoreImageTraining(firstProject.id, data); }) .then(() => { return store.bulkStoreImageTraining(secondProject.id, data); }) .then(() => { return store.bulkStoreImageTraining(thirdProject.id, data); }); } let fakeTimer: sinon.SinonFakeTimers; before(async () => { fakeTimer = sinon.useFakeTimers({ now : Date.now(), shouldAdvanceTime : true, }); authStub = sinon.stub(auth, 'authenticate').callsFake(authNoOp); checkUserStub = sinon.stub(auth, 'checkValidUser').callsFake(authNoOp); requireSupervisorStub = sinon.stub(auth, 'requireSupervisor').callsFake(authNoOp); // @ts-ignore getStub = sinon.stub(requestPromise, 'get'); // @ts-ignore getStub.withArgs(sinon.match(/https:\/\/gateway-a.watsonplatform.net\/visual-recognition\/api\/v3\/classifiers\/.*/), sinon.match.any).callsFake(getClassifier); getStub.callThrough(); // @ts-ignore createStub = sinon.stub(requestPromise, 'post'); // @ts-ignore createStub.withArgs(sinon.match('https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers'), sinon.match.any).callsFake(createClassifier); // @ts-ignore deleteStub = sinon.stub(requestPromise, 'delete').callsFake(deleteClassifier); await store.init(); testServer = testapiserver(); return store.deleteBluemixCredentialsPoolForTests() .then(() => { return store.storeManagedClassTenant(classid, 10, 3, types.ClassTenantType.ManagedPool); }) .then(() => { return setupPoolCreds(); }) .then(() => { return setupProjects(); }) .then(() => { return setupTrainingData(); }); }); after(async () => { // deleting a visual rec model will automatically retry // after 20 minutes, so to stop mocha waiting 20 minutes // for this, we skip the clock forward 30 minutes before // ending the test fakeTimer.tick(1000 * 60 * 30); authStub.restore(); checkUserStub.restore(); requireSupervisorStub.restore(); await store.deleteEntireProject(userid, classid, firstProject); await store.deleteEntireProject(userid, classid, secondProject); await store.deleteEntireProject(userid, classid, thirdProject); await store.deleteClassTenant(classid); await store.deleteBluemixCredentialsPool(firstCredsId); await store.deleteBluemixCredentialsPool(secondCredsId); getStub.restore(); createStub.restore(); deleteStub.restore(); fakeTimer.restore(); return store.disconnect(); }); describe('visualrecognition', () => { it('should train a model', () => { return request(testServer) .post('/api/classes/' + classid + '/students/' + userid + '/projects/' + firstProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.CREATED) .then((res) => { assert(res.body.classifierid); assert(res.body.updated); assert(res.body.expiry); assert(new Date(res.body.updated).getTime() < new Date(res.body.expiry).getTime()); assert(res.body.credentialsid === firstCredsId || res.body.credentialsid === secondCredsId); assert.strictEqual(res.body.name, 'my_project_model'); assert.strictEqual(res.body.status, 'Training'); }); }); it('should get a model status', () => { return request(testServer) .get('/api/classes/' + classid + '/students/' + userid + '/projects/' + firstProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.OK) .then((res) => { assert.strictEqual(res.body.length, 1); assert(res.body[0].classifierid); assert(res.body[0].updated); assert(res.body[0].expiry); assert(res.body[0].credentialsid === firstCredsId || res.body[0].credentialsid === secondCredsId); assert.strictEqual(res.body[0].name, 'my_project_model'); assert.strictEqual(res.body[0].status, 'Available'); }); }); it('should update a model', () => { return request(testServer) .post('/api/classes/' + classid + '/students/' + userid + '/projects/' + firstProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.CREATED) .then((res) => { assert(res.body.classifierid); assert(res.body.updated); assert(res.body.expiry); assert(new Date(res.body.updated).getTime() < new Date(res.body.expiry).getTime()); assert(res.body.credentialsid === firstCredsId || res.body.credentialsid === secondCredsId); assert.strictEqual(res.body.name, 'my_project_model'); assert.strictEqual(res.body.status, 'Training'); }); }); it('should record failures', async () => { failCredsId = 'neither'; const timestamp = new Date().getTime(); log.debug({ timestamp }, 'Created timestamp'); await wait(); log.debug('Waited.'); log.debug('Getting credentials'); let first = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, firstCredsId); let second = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, secondCredsId); let firstCredsCheck = first as trainingtypes.BluemixCredentialsPool; let secondCredsCheck = second as trainingtypes.BluemixCredentialsPool; const firstCredsCheckTime = firstCredsCheck.lastfail.getTime(); const secondCredsCheckTime = secondCredsCheck.lastfail.getTime(); log.debug({ firstCredsCheckTime, secondCredsCheckTime, timestamp }, 'Timestamps'); assert(firstCredsCheckTime < timestamp); assert(secondCredsCheckTime < timestamp); log.debug('Submitting model training'); return request(testServer) .post('/api/classes/' + classid + '/students/' + userid + '/projects/' + secondProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.CREATED) .then(async (res) => { log.debug({ body : res.body }, 'Response'); assert(res.body.classifierid); assert(res.body.updated); assert(res.body.expiry); assert(new Date(res.body.updated).getTime() < new Date(res.body.expiry).getTime()); assert(res.body.credentialsid === firstCredsId || res.body.credentialsid === secondCredsId); assert(res.body.credentialsid !== failCredsId); assert.strictEqual(res.body.name, 'my_project_model'); assert.strictEqual(res.body.status, 'Training'); first = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, firstCredsId); second = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, secondCredsId); firstCredsCheck = first as trainingtypes.BluemixCredentialsPool; secondCredsCheck = second as trainingtypes.BluemixCredentialsPool; if (failCredsId === firstCredsId) { assert(firstCredsCheck.lastfail.getTime() > timestamp); assert(secondCredsCheck.lastfail.getTime() === secondCredsCheckTime); } else if (failCredsId === secondCredsId) { assert(secondCredsCheck.lastfail.getTime() > timestamp); assert(firstCredsCheck.lastfail.getTime() === firstCredsCheckTime); } else { assert.fail('No credentials recorded failure'); } }); }); it('should delete a model', () => { return request(testServer) .get('/api/classes/' + classid + '/students/' + userid + '/projects/' + secondProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.OK) .then((res) => { assert.strictEqual(res.body.length, 1); return request(testServer) .delete('/api/classes/' + classid + '/students/' + userid + '/projects/' + secondProject.id + '/models/' + res.body[0].classifierid) .expect(httpstatus.NO_CONTENT); }) .then(() => { return request(testServer) .get('/api/classes/' + classid + '/students/' + userid + '/projects/' + secondProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.OK); }) .then((res) => { assert.strictEqual(res.body.length, 0); }); }); it('should handle exhausted pool creds', async() => { failCredsId = 'all'; let first = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, firstCredsId); let second = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, secondCredsId); let firstCredsCheck = first as trainingtypes.BluemixCredentialsPool; let secondCredsCheck = second as trainingtypes.BluemixCredentialsPool; const firstCredsCheckTime = firstCredsCheck.lastfail.getTime(); const secondCredsCheckTime = secondCredsCheck.lastfail.getTime(); return request(testServer) .post('/api/classes/' + classid + '/students/' + userid + '/projects/' + thirdProject.id + '/models') .expect('Content-Type', /json/) .expect(httpstatus.CONFLICT) .then(async (res) => { assert.deepStrictEqual(res.body, { code: 'MLMOD16', error: 'Your class is sharing Watson Visual Recognition "API keys" with many other schools, and ' + 'unfortunately there are currently none available. ' + 'Please let your teacher or group leader know that you will have to train ' + 'your machine learning model later', }); first = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, firstCredsId); second = await store.getBluemixCredentialsById(types.ClassTenantType.ManagedPool, secondCredsId); firstCredsCheck = first as trainingtypes.BluemixCredentialsPool; secondCredsCheck = second as trainingtypes.BluemixCredentialsPool; assert(firstCredsCheck.lastfail.getTime() > firstCredsCheckTime); assert(secondCredsCheck.lastfail.getTime() > secondCredsCheckTime); // more than one day assert(firstCredsCheck.lastfail.getTime() > (firstCredsCheckTime + 86400000)); assert(secondCredsCheck.lastfail.getTime() > (secondCredsCheckTime + 86400000)); // less than two days assert(firstCredsCheck.lastfail.getTime() < (firstCredsCheckTime + 172800000)); assert(secondCredsCheck.lastfail.getTime() < (secondCredsCheckTime + 172800000)); }); }); }); const getClassifier = (url: string/*, options: express.Request */) => { assert(url.endsWith(workspaceId), url + ' should end with ' + workspaceId); const classifierDate = new Date(); classifierDate.setMilliseconds(0); return new Promise((resolve) => { resolve({ classifier_id : 'good', name : 'my_project_model', owner : 'bob', status : 'ready', created : classifierDate.toISOString(), classes : [ { class : 'rock' }, { class : 'paper' }, ], }); }); }; const createClassifier = (url: string, options: visrec.LegacyTrainingRequest) => { return new Promise((resolve, reject) => { assert(url); assert(options.formData); if (failCredsId === 'all') { return reject({ error : { error : { description : 'Cannot execute learning task. : this plan instance can have only 1 custom classifier(s), and 1 already exist.', code : 400, error_id : 'input_error', }, }, statusCode : 400, status : 400, }); } if (options.formData.name === 'my other project') { if (failCredsId === 'neither') { if (options.qs.api_key === firstCredsApi) { failCredsId = firstCredsId; } else if (options.qs.api_key === secondCredsApi) { failCredsId = secondCredsId; } else { assert.fail('Unexpected credentials'); } return reject({ error : { error : { description : 'Cannot execute learning task. : this plan instance can have only 1 custom classifier(s), and 1 already exist.', code : 400, error_id : 'input_error', }, }, statusCode : 400, status : 400, }); } else { if (options.qs.api_key === firstCredsApi) { assert.strictEqual(failCredsId, secondCredsId); } else if (options.qs.api_key === secondCredsApi) { assert.strictEqual(failCredsId, firstCredsId); } else { assert.fail('Unexpected credentials'); } const classifierDate = new Date(); classifierDate.setMilliseconds(0); workspaceId = uuid(); return resolve({ classifier_id : workspaceId, name : 'my_project_model', owner : 'bob', status : 'training', created : classifierDate.toISOString(), classes : [ { class : 'spider' }, { class : 'fly' }, ], }); } } const newClassifierDate = new Date(); newClassifierDate.setMilliseconds(0); workspaceId = uuid(); resolve({ classifier_id : workspaceId, name : 'my_project_model', owner : 'bob', status : 'training', created : newClassifierDate.toISOString(), classes : [ { class : 'spider' }, { class : 'fly' }, ], }); }); }; const deleteClassifier = (url: string) => { assert(url); return Promise.resolve(); }; const wait = () => { return new Promise((resolve) => { setTimeout(resolve, 500); }); }; });
the_stack
import { HelperEventEmitter, Notifier } from 'coc-helper'; import { Buffer, Disposable, disposeAll, ExtensionContext, Window, workspace, } from 'coc.nvim'; import pFilter from 'p-filter'; import { ActionExplorer } from './actions/actionExplorer'; import { loadGlobalActions } from './actions/globalActions'; import { MappingMode } from './actions/types'; import { argOptions, ResolvedArgs } from './arg/argOptions'; import { ArgContentWidthTypes, Args } from './arg/parseArgs'; import { ExplorerConfig, getRevealWhenOpen } from './config'; import { BuffuerContextVars } from './contextVariables'; import { doUserAutocmd, doUserAutocmdNotifier, onEvent } from './events'; import { ExplorerManager } from './explorerManager'; import { FloatingPreview } from './floating/floatingPreview'; import { quitHelp, showHelp } from './help'; import { HighlightExplorer } from './highlight/highlightExplorer'; import { LocatorExplorer } from './locator/locatorExplorer'; import { Rooter, RooterOpened } from './rooter'; import './source/load'; import { BaseTreeNode, ExplorerSource } from './source/source'; import { sourceManager } from './source/sourceManager'; import { ExplorerOpenOptions } from './types'; import { closeWinByBufnrNotifier, currentBufnr, logger, normalizePath, sum, winByWinid, winidByWinnr, winnrByBufnr, } from './util'; import { RendererExplorer } from './view/rendererExplorer'; import { ViewExplorer } from './view/viewExplorer'; export class Explorer implements Disposable { nvim = workspace.nvim; context: ExtensionContext; inited: BuffuerContextVars<boolean>; sourceWinid: BuffuerContextVars<number>; sourceBufnr: BuffuerContextVars<number>; buffer: Buffer; floatingPreview: FloatingPreview; contentWidth = 0; action = new ActionExplorer(this); highlight = new HighlightExplorer(this); view = new ViewExplorer(this); locator = new LocatorExplorer(this); events = new HelperEventEmitter<{ 'open-pre': () => void | Promise<void>; 'first-open-pre': () => void | Promise<void>; 'open-post': () => void | Promise<void>; 'first-open-post': () => void | Promise<void>; }>(logger); firstOpened = false; rooter?: RooterOpened; private disposables: Disposable[] = []; private root_?: string; private args_?: Args; private argValues_?: ResolvedArgs; private isFloating_?: boolean; private sources_?: ExplorerSource<any>[]; private prevArgSourcesEnabledJson?: string; private isHide = false; private static genExplorerPosition( args: ResolvedArgs, specialSize?: [width?: number, height?: number], ) { let width: number = 0; let height: number = 0; let left: number = 0; let top: number = 0; if (args.position.name !== 'floating') { width = specialSize?.[0] ?? args.width; } else { width = specialSize?.[0] ?? args.floatingWidth; height = specialSize?.[1] ?? args.floatingHeight; const [vimWidth, vimHeight] = [ workspace.env.columns, workspace.env.lines - workspace.env.cmdheight, ]; if (width <= 0) { width = vimWidth + width; } if (height <= 0) { height = vimHeight + height; } const floatingPosition = args.floatingPosition; if (floatingPosition === 'left-center') { left = 0; top = (vimHeight - height) / 2; } else if (floatingPosition === 'center') { left = (vimWidth - width) / 2; top = (vimHeight - height) / 2; } else if (floatingPosition === 'right-center') { left = vimWidth - width; top = (vimHeight - height) / 2; } else if (floatingPosition === 'center-top') { left = (vimWidth - width) / 2; top = 0; } else { [left, top] = floatingPosition; } } return { width, height, top, left }; } static async create( explorerManager: ExplorerManager, argValues: ResolvedArgs, config: ExplorerConfig, ) { explorerManager.maxExplorerID += 1; const { width, height, top, left } = this.genExplorerPosition(argValues); const [bufnr, borderBufnr]: [ number, number | undefined, ] = await workspace.nvim.call('coc_explorer#open_explorer', [ explorerManager.maxExplorerID, argValues.position, { width, height, left, top, focus: argValues.focus, border_enable: config.get('floating.border.enable'), border_chars: config.get('floating.border.chars'), title: config.get('floating.border.title'), } as ExplorerOpenOptions, ]); const explorer = new Explorer( explorerManager.maxExplorerID, explorerManager, bufnr, borderBufnr, config, ); await explorer.inited.set(true); return explorer; } constructor( public explorerID: number, public explorerManager: ExplorerManager, public bufnr: number, public borderBufnr: number | undefined, public config: ExplorerConfig, ) { this.context = explorerManager.context; this.buffer = this.nvim.createBuffer(this.bufnr); this.inited = new BuffuerContextVars<boolean>('inited', this.buffer); this.sourceWinid = new BuffuerContextVars<number>( 'sourceWinid', this.buffer, ); this.sourceBufnr = new BuffuerContextVars<number>( 'sourceBufnr', this.buffer, ); this.floatingPreview = new FloatingPreview(this); if (borderBufnr) { this.disposables.push( onEvent('BufWinLeave', async (curBufnr) => { if (curBufnr === bufnr) { await closeWinByBufnrNotifier([borderBufnr]).run(); } }), ); } loadGlobalActions(this.action); } dispose() { this.floatingPreview.dispose(); this.disposables.forEach((s) => s.dispose()); } get root(): string { if (!this.root_) { throw Error('Explorer root not initialized yet'); } return this.root_; } get args(): Args { if (!this.args_) { throw Error('Explorer args not initialized yet'); } return this.args_; } get argValues(): ResolvedArgs { if (!this.argValues_) { throw Error('Explorer argValues not initialized yet'); } return this.argValues_; } get isFloating(): boolean { if (this.isFloating_ === undefined) { throw Error('Explorer isFloating not initialized yet'); } return this.isFloating_; } get sources(): ExplorerSource<BaseTreeNode<any>>[] { if (!this.sources_) { throw Error('Explorer sources not initialized yet'); } return this.sources_; } get height() { return sum(this.sources.map((s) => s.height)); } get win(): Promise<Window | undefined> { return this.winid.then(winByWinid); } /** * vim winnr of explorer */ get winnr(): Promise<number | undefined> { return winnrByBufnr(this.bufnr); } /** * vim winid of explorer */ get winid(): Promise<number | undefined> { return this.winnr.then(winidByWinnr); } get borderWin(): Promise<Window | undefined> { return this.borderWinid.then(winByWinid); } get borderWinnr() { return winnrByBufnr(this.borderBufnr); } get borderWinid() { return this.borderWinnr.then(winidByWinnr); } async sourceWinnr() { const winid = await this.sourceWinid.get(); if (!winid) { return undefined; } const winnr = (await this.nvim.call('win_id2win', [winid])) as number; if (winnr <= 0 || (await this.explorerManager.winnrs()).includes(winnr)) { return; } return winnr; } async sourceBufnrBySourceWinid() { const winid = await this.sourceWinid.get(); if (!winid) { return; } const bufnr = (await this.nvim.call('winbufnr', [winid])) as number; if (bufnr <= 0) { return; } return bufnr; } async sourceBuffer() { const bufnr = await this.sourceBufnr.get(); if (!bufnr) { return; } return this.nvim.createBuffer(bufnr); } visible() { const node = this.explorerManager.bufManager.getBufferNode(this.bufnr); return node?.visible; } async refreshWidth() { const window = await this.win; if (!window) { return; } const setWidth = async ( contentWidthType: ArgContentWidthTypes, contentWidth: number, ) => { if (contentWidth <= 0) { let contentBaseWidth: number | undefined; if (contentWidthType === 'win-width') { contentBaseWidth = await window.width; if ( ((await window.getOption('relativenumber')) as boolean) || ((await window.getOption('number')) as boolean) ) { contentBaseWidth -= (await window.getOption( 'numberwidth', )) as number; } } else if (contentWidthType === 'vim-width') { contentBaseWidth = (await workspace.nvim.eval('&columns')) as number; } if (contentBaseWidth) { this.contentWidth = contentBaseWidth + contentWidth; return true; } } else { this.contentWidth = contentWidth; return true; } }; if (this.isFloating) { if (await setWidth('win-width', this.argValues.floatingContentWidth)) { return; } } if ( await setWidth( this.argValues.contentWidthType, this.argValues.contentWidth, ) ) { return; } } async resize(size?: [width?: number, height?: number]) { const dimension = Explorer.genExplorerPosition(this.argValues, size); const { top, left, width, height } = dimension; await this.nvim.call('coc_explorer#resize', [ this.bufnr, this.argValues.position, { width, height, left, top, border_bufnr: this.borderBufnr, border_enable: this.config.get('floating.border.enable'), border_chars: this.config.get('floating.border.chars'), title: this.config.get('floating.border.title'), } as ExplorerOpenOptions, ]); } /** * Focus on explorer window * @returns Whether the focus is successful */ async focus() { const win = await this.win; if (win) { // focus on explorer window await this.nvim.command(`${await win.number}wincmd w`); await this.resize(); return true; } return false; } async resume(argValues: ResolvedArgs) { const { width, height, top, left } = Explorer.genExplorerPosition( argValues, ); await this.nvim.call('coc_explorer#resume', [ this.bufnr, argValues.position, { width, height, left, top, focus: argValues.focus, border_bufnr: this.borderBufnr, border_enable: this.config.get('floating.border.enable'), border_chars: this.config.get('floating.border.chars'), title: this.config.get('floating.border.title'), } as ExplorerOpenOptions, ]); } async open(args: Args, rooter: Rooter, isFirst: boolean) { let firstOpen: boolean; if (!this.firstOpened) { firstOpen = true; this.firstOpened = true; } else { firstOpen = false; } if (firstOpen) { await this.events.fire('first-open-pre'); } await this.events.fire('open-pre'); await doUserAutocmd('CocExplorerOpenPre'); this.rooter = rooter.open(this); if (this.view.isHelpUI) { await this.quitHelp(); } await this.highlight.bootSyntax(); const sourcesChanged = await this.initArgs(args, this.rooter); for (const source of this.sources) { await source.bootOpen(isFirst); } await this.view.sync(async (r) => { const notifiers: Notifier[] = []; if (sourcesChanged) { notifiers.push(this.clearLinesNotifier()); } notifiers.push( await this.loadAllNotifier(r), ...(await Promise.all( r .rendererSources() .map((rs) => rs.source.openedNotifier(rs, isFirst)), )), ); await Notifier.runAll(notifiers); await doUserAutocmd('CocExplorerOpenPost'); await this.events.fire('open-post'); if (firstOpen) { await this.events.fire('first-open-post'); } }); } async tryQuitOnOpenNotifier() { if (this.argValues.quitOnOpen || this.isFloating) { return this.quitNotifier(); } return Notifier.noop(); } async tryQuitOnOpen() { return Notifier.run(this.tryQuitOnOpenNotifier()); } async hide() { this.isHide = true; await this.quit(true); } async show() { if (this.isHide) { this.isHide = false; await this.resume(this.argValues); } } async quitNotifier(isHide = false) { if (!isHide) { await doUserAutocmd('CocExplorerQuitPre'); } const sourceWinnr = await this.sourceWinnr(); const bufnr = await currentBufnr(); return Notifier.create(() => { if (sourceWinnr && this.bufnr === bufnr) { this.nvim.command(`${sourceWinnr}wincmd w`, true); } closeWinByBufnrNotifier([this.bufnr]).notify(); if (!isHide) { doUserAutocmdNotifier('CocExplorerQuitPost').notify(); } }); } async quit(isHide = false) { return Notifier.run(await this.quitNotifier(isHide)); } /** * initialize root */ private async initRoot(argValues: ResolvedArgs, rooter: RooterOpened) { const root = argValues.rootUri; if (root) { this.root_ = normalizePath(root); return; } let reveal: string | undefined; if (getRevealWhenOpen(this.config, this.argValues.revealWhenOpen)) { reveal = await this.revealPath(); } const resolvedRoot = await rooter.resolveRoot( reveal, this.argValues.rootStrategies, ); if (resolvedRoot) { this.root_ = normalizePath(resolvedRoot); return; } this.root_ = normalizePath(workspace.cwd); } /** * initialize arguments * * @return sources changed */ private async initArgs(args: Args, rooter: RooterOpened): Promise<boolean> { this.args_ = args; this.argValues_ = await args.values(argOptions); await this.initRoot(this.argValues_, rooter); const argSources = await args.value(argOptions.sources); if (!argSources) { return false; } const enabledArgSources = await pFilter(argSources, (s) => sourceManager.enabled(s.name), ); const argSourcesEnabledJson = JSON.stringify(enabledArgSources); if ( this.prevArgSourcesEnabledJson && this.prevArgSourcesEnabledJson === argSourcesEnabledJson ) { return false; } this.prevArgSourcesEnabledJson = argSourcesEnabledJson; disposeAll(this.sources_ ?? []); this.sources_ = enabledArgSources.map((sourceArg) => sourceManager.createSource(sourceArg.name, this, sourceArg.expand), ); const position = await this.args_.value(argOptions.position); this.isFloating_ = position.name === 'floating'; return true; } async revealPath() { const revealPath = await this.args.value(argOptions.reveal); if (revealPath) { return revealPath; } else { const buf = await this.sourceBuffer(); if (buf) { return ( this.explorerManager.bufManager.getBufferNode(buf.id)?.fullpath ?? undefined ); } return; } } async getSelectedOrCursorLineIndexes(mode: MappingMode) { const lineIndexes = new Set<number>(); const document = await workspace.document; if (mode === 'v') { const range = await workspace.getSelectedRange('v', document); if (range) { for ( let lineIndex = range.start.line; lineIndex <= range.end.line; lineIndex++ ) { lineIndexes.add(lineIndex); } return lineIndexes; } } await this.view.refreshLineIndex(); lineIndexes.add(this.view.currentLineIndex); return lineIndexes; } findSourceByLineIndex( lineIndex: number, ): { source: ExplorerSource<any>; sourceIndex: number } { const sourceIndex = this.sources.findIndex( (source) => lineIndex < source.view.endLineIndex, ); if (sourceIndex === -1) { const index = this.sources.length - 1; return { source: this.sources[index], sourceIndex: index }; } else { return { source: this.sources[sourceIndex], sourceIndex }; } } lineIndexesGroupBySource(lineIndexes: number[] | Set<number>) { const groups = new Map< number, { source: ExplorerSource<any>; lineIndexes: number[]; } >(); for (const line of lineIndexes) { const { source, sourceIndex } = this.findSourceByLineIndex(line); let group = groups.get(sourceIndex); if (!group) { group = { source, lineIndexes: [line], }; groups.set(sourceIndex, group); } group.lineIndexes.push(line); } return [...groups.values()]; } setLinesNotifier(lines: string[], start: number, end: number) { return Notifier.create(() => { this.nvim.call( 'coc_explorer#util#buf_set_lines_skip_cursor', [this.bufnr, start, end, false, lines], true, ); }); } clearLinesNotifier() { return this.setLinesNotifier([], 0, -1); } async loadAllNotifier(renderer: RendererExplorer, { render = true } = {}) { this.locator.mark.removeAll(); const notifiers = await Promise.all( renderer .rendererSources() .map((r) => r.source.loadNotifier(r, r.view.rootNode, { render: false }), ), ); if (render) { notifiers.push(await renderer.renderAllNotifier()); } return Notifier.combine(notifiers); } async render() { return this.view.sync((renderer) => Notifier.run(renderer.renderAllNotifier()), ); } async showHelp(source: ExplorerSource<any>) { return showHelp(this, source); } async quitHelp() { return quitHelp(this); } }
the_stack
import * as packageUtils from "../util/package"; import merge = require("lodash.merge"); import includes = require("lodash.includes"); import * as path from "path"; import { IEyeglass } from "../IEyeglass"; import { SassImplementation } from "../util/SassImplementation"; import type { FunctionDeclarations } from "node-sass"; import packageJson = require("package-json"); import AssetsCollection from "../assets/AssetsCollection"; import { Dict, isPresent } from "../util/typescriptUtils"; import { realpathSync } from "../util/perf"; import { SemVer } from "semver"; type PackageJson = packageJson.FullVersion; const rInvalidName = /\.(?:sass|s?css)$/; const EYEGLASS_KEYWORD: "eyeglass-module" = "eyeglass-module"; export interface DiscoverOptions { isRoot: boolean; dir: string; pkg?: packageUtils.Package; } export interface EyeglassModuleExports { name?: string; functions?: FunctionDeclarations; assets?: AssetsCollection; sassDir?: string; eyeglass?: { needs?: string; }; } interface EyeglassModuleOptionsFromPackageJSON { inDevelopment?: boolean; name?: string; exports?: string | false; sassDir?: string; needs?: string; } interface PackageEyeglassOption { eyeglass?: string | EyeglassModuleOptionsFromPackageJSON; } type PackageJsonWithEyeglassOptions = PackageJson & PackageEyeglassOption; type EyeglassOptionInPackageJSON = PackageJsonWithEyeglassOptions["eyeglass"]; export type EyeglassModuleMain = (eyeglass: IEyeglass, sass: SassImplementation) => EyeglassModuleExports; export type ModuleSpecifier = ModuleReference | ManualModuleOptions; export interface ModuleReference { path: string; /** * XXX I don't think dependencies are ever actually * passed along with a path reference but the code allows it. */ dependencies?: Array<EyeglassModule>; isEyeglassModule?: boolean; } export interface ManualModuleOptions { /** * The name of the module. */ name?: string; /** * The function that would normally be exported from the * eyeglass exports file. */ main?: EyeglassModuleMain | null; /** * If a main function is provided this path to the * filename where it is defined should be provided * for better error messages in some situations. */ mainPath?: string | undefined; /** * The directory where sass files are found for this module. */ sassDir?: string; /** * A version for this manual module. */ version?: string; eyeglass?: { /** * The name of the module for the purpose of importing * from sass files. */ name?: string; /** * Alternative way to specify the directory where sass files are found for * this module. */ sassDir?: string; /** * The semver dependency on eyeglass's module API. */ needs?: string; }; } interface IEyeglassModule { inDevelopment: boolean; /** * The resolved name of the eyeglass module. */ name: string; /** * The name of the package which may be different from the name of the * eyeglass module. */ rawName: string; /** * Options for the module that were passed from package.json */ eyeglass: EyeglassModuleOptionsFromPackageJSON; /** * The absolute path to this module. */ path: string; /** * The exports function used to help initialize this module. */ main?: EyeglassModuleMain | null; /** * The path to main/exports function. Used for debugging. */ mainPath?: string | null; /** * Whether this is an eyeglass module. Manual modules * and the application itself are modules where this is false. */ isEyeglassModule: boolean; /** * Whether this is the project root. */ isRoot: boolean; /** * The version of this module. */ version: string | undefined; /** * The other modules this module depends on. The dependency tree is * eventually flattened with a semver resolution to select a single instance * of shared transitive dependencies. */ dependencies: Dict<EyeglassModule>; /** * Where the sass files are. `@import "<module name>"` would import the index * sass file from that directory. Imports of paths relative to the module * name are imported relative to this directory. */ sassDir?: string; } export function isModuleReference(mod: unknown): mod is ModuleReference { return typeof mod === "object" && mod !== null && typeof (<ModuleReference>mod).path === "string"; } export default class EyeglassModule implements IEyeglassModule, EyeglassModuleExports { inDevelopment: boolean; dependencies: Dict<EyeglassModule>; eyeglass: EyeglassModuleOptionsFromPackageJSON; isEyeglassModule: boolean; isRoot: boolean; name: string; path: string; rawName: string; version: string | undefined; sassDir?: string; main?: EyeglassModuleMain | null; mainPath?: string | null; /** only present after calling `init()` */ functions?: FunctionDeclarations; /** only present after calling `init()` */ assets?: AssetsCollection; semver: SemVer; constructor( modArg: ModuleReference | ManualModuleOptions, discoverModules?: (opts: DiscoverOptions) => Dict<EyeglassModule> | null, isRoot: boolean = false ) { // some defaults let mod: IEyeglassModule = merge({ eyeglass: {} }, modArg as IEyeglassModule); // if we were given a path, resolve it to the package.json if (isModuleReference(mod)) { let pkg = packageUtils.getPackage<PackageEyeglassOption>(mod.path); // if pkg.data is empty, this is an invalid path, so throw an error if (!pkg.data) { throw new Error("Could not find a valid package.json at " + mod.path); } let modulePath = realpathSync(path.dirname(pkg.path)); mod = merge( { isEyeglassModule: EyeglassModule.isEyeglassModule(pkg.data), inDevelopment: false, isRoot }, mod, { path: modulePath, name: getModuleName(pkg.data), rawName: pkg.data.name, version: pkg.data.version, // only resolve dependencies if we were given a discoverModules function dependencies: discoverModules && discoverModules({ dir: modulePath, isRoot: isRoot }) || mod.dependencies, // preserve any passed in dependencies eyeglass: normalizeEyeglassOptions(pkg.data.eyeglass, modulePath) } ); if (mod.isEyeglassModule) { let moduleMain = getModuleExports(pkg.data, modulePath); let mainInfo: Pick<EyeglassModule, "main" | "mainPath"> = { main: moduleMain && (require(moduleMain) as EyeglassModuleMain) || null, mainPath: moduleMain }; merge(mod, mainInfo); if (rInvalidName.test(mod.name)) { throw new Error("An eyeglass module cannot contain an extension in it's name: " + mod.name); } } } // if a sassDir is specified in eyeglass options, it takes precedence mod.sassDir = mod.eyeglass.sassDir || mod.sassDir; // set the rawName if it's not already set mod.rawName = mod.rawName || mod.name; // these are handled by merge but are here to make the compiler happy // TODO: Rewrite this to not use the intermediate object. this.dependencies = mod.dependencies; this.eyeglass = mod.eyeglass; this.isEyeglassModule = mod.isEyeglassModule; this.name = mod.name; this.path = mod.path; this.rawName = mod.rawName; this.version = mod.version; this.inDevelopment = mod.inDevelopment; this.isRoot = mod.isRoot; // merge the module properties into the instance merge(this, mod); if (this.version) { this.semver = new SemVer(this.version); } else { this.semver = new SemVer("0.0.0"); } } /** * initializes the module with the given engines * * @param {Eyeglass} eyeglass - the eyeglass instance * @param {Function} sass - the sass engine */ init(eyeglass: IEyeglass, sass: SassImplementation): void { merge(this, this.main && this.main(eyeglass, sass)); } /** * whether or not the given package is an eyeglass module * * @param {Object} pkg - the package.json * @returns {Boolean} whether or not it is an eyeglass module */ static isEyeglassModule(pkg: PackageJson | undefined | null): boolean { return !!(isPresent(pkg) && includes(pkg.keywords, EYEGLASS_KEYWORD)); } hasModulePath(path: string): boolean { if (this.path === path) { return true; } let keys = this.dependencies ? Object.keys(this.dependencies) : []; for (let depKey of keys) { let dep = this.dependencies[depKey]; if (dep instanceof EyeglassModule && dep.hasModulePath(path)) { return true; } } return false; } } /** * given a package.json reference, gets the Eyeglass module name * * @param {Object} pkg - the package.json reference * @returns {String} the name of the module */ function getModuleName(pkg: PackageJson & PackageEyeglassOption): string | undefined { // check for `eyeglass.name` first, otherwise use `name` return normalizeEyeglassOptions(pkg.eyeglass).name || pkg.name; } /** * normalizes a given `eyeglass` reference from a package.json * * @param {Object} options - The eyeglass options from the package.json * @param {String} pkgPath - The location of the package.json. * @returns {Object} the normalized options */ function normalizeEyeglassOptions(options: EyeglassOptionInPackageJSON, pkgPath?: string): EyeglassModuleOptionsFromPackageJSON { let normalizedOpts: EyeglassModuleOptionsFromPackageJSON; if (typeof options === "object") { normalizedOpts = options; } else if (typeof options === "string") { // if it's a string, treat it as the export normalizedOpts = { exports: options }; } else { normalizedOpts = {}; } if (pkgPath && normalizedOpts.sassDir) { normalizedOpts.sassDir = path.resolve(pkgPath, normalizedOpts.sassDir); } return normalizedOpts; } /** * gets the export from a given `eyeglass` reference from a package.json * * @param {Object} options - the eyeglass options from the package.json * @returns {Object} the normalized options */ function getExportsFileFromOptions(options: EyeglassOptionInPackageJSON): string | false | undefined { return normalizeEyeglassOptions(options).exports; } /** * gets the export for a given package.json * * @param {Object} pkg - the package.json * @param {String} modulePath - the path to the module * @returns {String} the export file to use */ function getModuleExports(pkg: PackageJsonWithEyeglassOptions, modulePath: string): string | null { let exportsFile = getExportsFileFromOptions(pkg.eyeglass); if (exportsFile === false) { return null; } else { exportsFile = exportsFile || pkg.main; } if (exportsFile) { return path.join(modulePath, exportsFile); } else { return null; } }
the_stack
import path from 'path'; import { matcherHint, RECEIVED_COLOR as red, EXPECTED_COLOR as green, matcherErrorMessage, printWithType, printExpected, } from 'jest-matcher-utils'; import { joinWithNewLines, str, } from '../../../../../commonTestResources/utils'; import jestOpenAPI from '../../..'; const expectReceivedToSatisfySchemaInApiSpec = matcherHint( 'toSatisfySchemaInApiSpec', undefined, 'schemaName', { comment: "Matches 'received' to a schema defined in your API spec, then validates 'received' against it", isNot: false, }, ); const expectReceivedNotToSatisfySchemaInApiSpec = matcherHint( 'toSatisfySchemaInApiSpec', undefined, 'schemaName', { comment: "Matches 'received' to a schema defined in your API spec, then validates 'received' against it", isNot: true, }, ); const openApiSpecsDir = path.resolve( '../../commonTestResources/exampleOpenApiFiles/valid/satisfySchemaInApiSpec', ); const openApiSpecs = [ { openApiVersion: 2, pathToApiSpec: path.join(openApiSpecsDir, 'openapi2.json'), }, { openApiVersion: 3, pathToApiSpec: path.join(openApiSpecsDir, 'openapi3.yml'), }, ]; openApiSpecs.forEach((spec) => { const { openApiVersion, pathToApiSpec } = spec; describe(`expect(obj).toSatisfySchemaInApiSpec(schemaName) (using an OpenAPI ${openApiVersion} spec)`, () => { beforeAll(() => { jestOpenAPI(pathToApiSpec); }); describe("when 'obj' matches a schema defined in the API spec, such that spec expects obj to", () => { describe('be a string', () => { const schemaName = 'StringSchema'; const expectedSchema = { type: 'string' }; describe("'obj' satisfies the spec", () => { const validObj = 'string'; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( new Error( // prettier-ignore joinWithNewLines( expectReceivedNotToSatisfySchemaInApiSpec, `expected ${red('received')} not to satisfy the '${schemaName}' schema defined in your API spec`, `${red('received')} was: ${red('\'string\'')}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ), ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = 123; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( new Error( // prettier-ignore joinWithNewLines( expectReceivedToSatisfySchemaInApiSpec, `expected ${red('received')} to satisfy the '${schemaName}' schema defined in your API spec`, `${red('received')} did not satisfy it because: object must be string`, `${red('received')} was: ${red(123)}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ), ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); describe('be an integer', () => { const schemaName = 'IntegerSchema'; const expectedSchema = { type: 'integer' }; describe("'obj' satisfies the spec", () => { const validObj = 123; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} was: ${red(123)}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = 'must be integer'; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} did not satisfy it because: object must be integer`, `${red('received')} was: ${red('\'must be integer\'')}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); describe('be a simple object', () => { const schemaName = 'SimpleObjectSchema'; const expectedSchema = { type: 'object', required: ['property1'], properties: { property1: { type: 'string' } }, }; describe("'obj' satisfies the spec", () => { const validObj = { property1: 'string' }; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not and outputs a useful error message', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} was: ${red(str(validObj))}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = { property1: 123 }; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} did not satisfy it because: property1 must be string`, `${red('received')} was: ${red(str(invalidObj))}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); describe('satisfy a schema referencing another schema', () => { const schemaName = 'SchemaReferencingAnotherSchema'; const definitions = openApiVersion === 2 ? 'definitions' : 'components/schemas'; const expectedSchema = { required: ['property1'], properties: { property1: { $ref: `#/${definitions}/StringSchema` }, }, }; describe("'obj' satisfies the spec", () => { const validObj = { property1: 'string' }; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not and outputs a useful error message', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} was: ${red(str(validObj))}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = { property1: 123 }; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore joinWithNewLines( `${red('received')} did not satisfy it because: property1 must be string`, `${red('received')} was: ${red(str(invalidObj))}`, `The '${schemaName}' schema in API spec: ${green(str(expectedSchema))}`, ), ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); describe('satisfy allOf 2 schemas', () => { const schemaName = 'SchemaUsingAllOf'; describe("'obj' satisfies the spec", () => { const validObj = { property1: 'string', property2: 'string' }; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( `expected ${red('received')} not to satisfy`, ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = { property1: 'string', property2: 123 }; it('fails', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore `${red('received')} did not satisfy it because: property2 must be string`, ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); if (openApiVersion === 3) { describe('satisfy anyOf 2 schemas', () => { const schemaName = 'SchemaUsingAnyOf'; describe("'obj' satisfies the spec", () => { const validObj = { property1: 123, property2: 'string' }; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( `expected ${red('received')} not to satisfy`, ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = { property1: 123, property2: 123 }; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore `${red('received')} did not satisfy it because: property1 must be string, property2 must be string, object must match a schema in anyOf`, ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); describe('satisfy oneOf 2 schemas', () => { const schemaName = 'SchemaUsingOneOf'; describe("'obj' satisfies the spec", () => { const validObj = { property1: 123, property2: 'string' }; it('passes', () => { expect(validObj).toSatisfySchemaInApiSpec(schemaName); }); it('fails when using .not', () => { const assertion = () => expect(validObj).not.toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( `expected ${red('received')} not to satisfy`, ); }); }); describe("'obj' does not satisfy the spec", () => { const invalidObj = { property1: 'string', property2: 'string' }; it('fails and outputs a useful error message', () => { const assertion = () => expect(invalidObj).toSatisfySchemaInApiSpec(schemaName); expect(assertion).toThrow( // prettier-ignore `${red('received')} did not satisfy it because: object must match exactly one schema in oneOf`, ); }); it('passes when using .not', () => { expect(invalidObj).not.toSatisfySchemaInApiSpec(schemaName); }); }); }); } }); describe("when 'obj' matches NO schemas defined in the API spec", () => { const obj = 'foo'; it('fails', () => { const assertion = () => expect(obj).toSatisfySchemaInApiSpec('NonExistentSchema'); expect(assertion).toThrow( new Error( matcherErrorMessage( expectReceivedToSatisfySchemaInApiSpec, `${green('schemaName')} must match a schema in your API spec`, printWithType('schemaName', 'NonExistentSchema', printExpected), ), ), ); }); it('fails when using .not', () => { const assertion = () => expect(obj).not.toSatisfySchemaInApiSpec('NonExistentSchema'); expect(assertion).toThrow( new Error( matcherErrorMessage( expectReceivedNotToSatisfySchemaInApiSpec, `${green('schemaName')} must match a schema in your API spec`, printWithType('schemaName', 'NonExistentSchema', printExpected), ), ), ); }); }); }); });
the_stack
import generate from "@babel/generator"; import { arrayExpression, assignmentExpression, binaryExpression, blockStatement, booleanLiteral, callExpression, conditionalExpression, expressionStatement, functionDeclaration, functionExpression, identifier, ifStatement, isExpression as isExpression_, isFunction, isLiteral, isReturnStatement, logicalExpression, memberExpression, nullLiteral, numericLiteral, objectExpression, objectMethod, objectProperty, returnStatement, sequenceExpression, stringLiteral, traverse, unaryExpression, updateExpression, variableDeclaration, variableDeclarator, Expression, Identifier, MemberExpression, Node, ObjectMethod, ObjectProperty, PatternLike, SpreadElement, Statement, ThisExpression } from "@babel/types"; import { Term } from "./ast"; import { functionize, insertFunction, FunctionBuilder } from "./functions"; import { parseFunctionType, parseType } from "./parse"; import { reifyType, withPossibleRepresentations, PossibleRepresentation, ProtocolConformance, ProtocolConformanceMap, ReifiedType, TypeMap } from "./reified"; import { addVariable, lookup, mangleName, mappedValueForName, rootScope, uniqueName, DeclarationFlags, MappedNameValue, Scope } from "./scope"; import { Function, Type } from "./types"; import { concat, expectLength, lookupForMap } from "./utils"; export type ArgGetter = (index: number, desiredName?: string) => Value; const isExpression = isExpression_ as (node: Node) => node is Expression; export interface Position { line: number; column: number; } export interface Location { start: Position; end: Position; } interface ValueKind<T extends string> { kind: T; location?: Location; } const locationRangeRegex = /^(.*):(\d+):(\d+)$/; function parseLineAndColumn(position: string): Position { const matched = position.match(locationRangeRegex); if (matched === null) { throw new Error(`Source range does not match expected format: ${position}`); } expectLength(matched as ReadonlyArray<string>, 4); return { line: parseInt(matched[2], 10), column: parseInt(matched[3], 10), }; } export function locationForTerm(term: Term): Location | undefined { if (Object.hasOwnProperty.call(term.properties, "range")) { const range = term.properties.range; if (typeof range === "object" && !Array.isArray(range) && Object.hasOwnProperty.call(range, "from") && Object.hasOwnProperty.call(range, "to")) { return { start: parseLineAndColumn(range.from), end: parseLineAndColumn(range.to), }; } } return undefined; } type LocationSource = Location | Term | null; function readLocation(source?: LocationSource): Location | undefined { if (typeof source === "undefined" || source === null) { return undefined; } return !Object.hasOwnProperty.call(source, "properties") ? source as unknown as Location : locationForTerm(source as unknown as Term); } export interface ExpressionValue extends ValueKind<"expression"> { expression: Expression; } export function expr(expression: Identifier | ThisExpression, location?: LocationSource): VariableValue; export function expr(expression: Expression, location?: LocationSource): ExpressionValue | VariableValue; export function expr(expression: Expression, location?: LocationSource): ExpressionValue | ReturnType<typeof variable> { if (expression.type === "Identifier" || expression.type === "ThisExpression" || (expression.type === "MemberExpression" && isPure(expression.object) && (!expression.computed || isPure(expression.property)))) { return variable(expression, location); } return { kind: "expression", expression: simplifyExpression(expression), location: expression.loc || readLocation(location) }; } export interface StatementsValue extends ValueKind<"statements"> { statements: Statement[]; location?: Location; } export function statements(body: Statement[], location?: LocationSource): StatementsValue | ReturnType<typeof expr> { if (body.length >= 1) { const lastStatement = body[body.length - 1]; if (lastStatement.type === "ReturnStatement") { const last = lastStatement.argument === null ? undefinedLiteral : lastStatement.argument; if (body.length === 1) { return expr(last, lastStatement.loc || location); } } } return { kind: "statements", statements: body, location: readLocation(location), }; } export interface CallableValue extends ValueKind<"callable"> { call: (scope: Scope, arg: ArgGetter, argTypes: Value[]) => Value; type: Function; } export function callable(callback: (scope: Scope, arg: ArgGetter, argTypes: Value[]) => Value, functionType: Function | string, location?: LocationSource): CallableValue { const type = typeof functionType === "string" ? parseFunctionType(functionType) : functionType; return { kind: "callable", call: callback, type, location: readLocation(location) }; } export interface VariableValue extends ValueKind<"direct"> { expression: Identifier | MemberExpression | ThisExpression; } export function variable(expression: Identifier | MemberExpression | ThisExpression, location?: LocationSource): VariableValue { return { kind: "direct", expression, location: expression.loc || readLocation(location) }; } export interface BoxedValue extends ValueKind<"boxed"> { contents: VariableValue | SubscriptValue; type: Value; } export function boxed(contents: Value, type: Value, location?: LocationSource): BoxedValue { if (contents.kind !== "direct" && contents.kind !== "subscript") { throw new TypeError(`Unable to box a ${contents.kind}`); } return { kind: "boxed", contents, type, location: readLocation(location) }; } export interface FunctionValue extends ValueKind<"function"> { name: string; parentType: Value | undefined; type: Function; substitutions: Value[]; } export function functionValue(name: string, parentType: Value | undefined, functionType: Function | string, substitutions: Value[] = [], location?: LocationSource): FunctionValue { const type = typeof functionType === "string" ? parseFunctionType(functionType) : functionType; return { kind: "function", name, parentType, type, substitutions, location: readLocation(location) }; } export interface TupleValue extends ValueKind<"tuple"> { values: Value[]; } export function tuple(values: Value[], location?: LocationSource): TupleValue { return { kind: "tuple", values, location: readLocation(location) }; } export interface SubscriptValue extends ValueKind<"subscript"> { getter: Value; setter: Value; args: Value[]; types: Value[]; } export function subscript(getter: Value, setter: Value, args: Value[], types: Value[], location?: LocationSource): SubscriptValue { return { kind: "subscript", getter, setter, args, types, location: readLocation(location) }; } export interface ConditionalValue extends ValueKind<"conditional"> { predicate: Value; consequent: Value; alternate: Value; } export function conditional(predicate: Value, consequent: Value, alternate: Value, scope: Scope, location?: LocationSource): Value { if (predicate.kind === "expression" && predicate.expression.type === "BooleanLiteral") { return annotateValue(predicate.expression.value ? consequent : alternate, location); } return { kind: "conditional", predicate, consequent, alternate, location: readLocation(location) }; } export function unary(operator: "!" | "-" | "~" | "delete" | "void", operand: Value, scope: Scope, location?: LocationSource): Value { return transform(operand, scope, (operandExpression) => expr(unaryExpression( operator, operandExpression, ), location)); } export type BinaryOperator = "+" | "-" | "*" | "/" | "%" | "<" | ">" | "<=" | ">=" | "&" | "|" | "^" | "==" | "===" | "!=" | "!==" | "<<" | ">>" | ">>>" | "**" | "in" | "instanceof"; export function binary(operator: BinaryOperator, left: Value, right: Value, scope: Scope, location?: LocationSource): Value { return transform(left, scope, (leftExpression) => expr(binaryExpression( operator, leftExpression, read(right, scope), ), location)); } export function logical(operator: "||" | "&&", left: Value, right: Value, scope: Scope, location?: LocationSource): Value { return transform(left, scope, (leftExpression) => expr(logicalExpression( operator, leftExpression, read(right, scope), ), location)); } const validIdentifier = /^[a-zA-Z$_][a-zA-Z$_0-9]*$/; export function member(object: VariableValue, property: string | number, scope: Scope, location?: LocationSource): VariableValue; export function member(object: Value | string, property: string | number | Value, scope: Scope, location?: LocationSource): Value; export function member(object: Value | string, property: string | number | Value, scope: Scope, location?: LocationSource): Value { const objectValue = typeof object === "string" ? expr(identifier(object)) : object; return transform(objectValue, scope, (expression) => { const idExpression = typeof property === "object" ? read(property, scope) : literal(property, location).expression; const builder = typeof expressionLiteralValue(idExpression) !== "undefined" && objectValue.kind === "direct" ? variable as typeof expr : expr; if (idExpression.type === "StringLiteral" && validIdentifier.test(idExpression.value)) { return builder(memberExpression( expression, identifier(idExpression.value), ), location); } return builder(memberExpression( expression, idExpression, true, ), location); }); } export interface CopiedValue extends ValueKind<"copied"> { value: Value; type: Value; } export function copy(value: Value, type: Value): CopiedValue { return { kind: "copied", value, type, }; } export interface TypeValue extends ValueKind<"type"> { type: Type; runtimeValue?: Value; } export function typeValue(typeOrString: Type | string, location?: LocationSource, runtimeValue?: Value): TypeValue { return { kind: "type", type: typeof typeOrString === "string" ? parseType(typeOrString) : typeOrString, runtimeValue, location: readLocation(location) }; } export interface ConformanceValue extends ValueKind<"conformance"> { type: Value; conformance: string; } export function conformance(type: Value, name: string, scope: Scope, location?: LocationSource): ConformanceValue { while (type.kind === "conformance") { type = type.type; } return { kind: "conformance", type, conformance: name, location: readLocation(location) }; } export interface OptionalValue extends ValueKind<"optional"> { type: Value; value: Value | undefined; } export function optional(type: Value, value: Value | undefined, location?: LocationSource): OptionalValue { return { kind: "optional", type, value, location: readLocation(location) }; } export function typeFromValue(value: Value, scope: Scope): ReifiedType { switch (value.kind) { case "type": return reifyType(value.type, scope); case "conformance": { const reified = typeFromValue(value.type, scope); const conformanceName = value.conformance; if (Object.hasOwnProperty.call(reified.conformances, conformanceName)) { const conformanceMap: ProtocolConformanceMap = Object.create(null); conformanceMap[conformanceName] = reified.conformances[conformanceName]; for (const requirement of reified.conformances[conformanceName].requirements) { if (!Object.hasOwnProperty.call(reified.conformances, requirement)) { throw new TypeError(`Missing ${requirement} conformance in ${stringifyValue(value.type)}`); } conformanceMap[requirement] = reified.conformances[requirement]; } return { functions: lookupForMap<FunctionBuilder | undefined>(reified.conformances[conformanceName].functions), conformances: withPossibleRepresentations(conformanceMap, PossibleRepresentation.All), innerTypes: {}, }; } else { return { conformances: withPossibleRepresentations({}, PossibleRepresentation.Object), functions(functionName) { return (innerScope, arg, name, types) => { const targetConformance = reifyType(conformanceName, scope).conformances[conformanceName]; const alternate = alternateMethodForKeyInConformance(name, targetConformance); const result = member(member(value.type, conformanceName, innerScope), mangleName(alternate !== undefined ? alternate.name : functionName).name, innerScope); if (types.length <= 0) { return result; } const args: Value[] = []; for (let i = 0; i < types.length; i++) { args.push(arg(i)); } return callable((innerMostScope, innerArg, argTypes) => { const calledMethod = call( result, concat(args, argTypes.map((_, i) => innerArg(i))), concat(types, argTypes), innerMostScope, ); if (alternate !== undefined && alternate.reassign) { // TODO: Store into runtime box return set( innerArg(0), calledMethod, scope, ); } return calledMethod; // TODO: Find proper return and argument types }, "() -> Void"); }; }, innerTypes: {}, }; } } default: { // TODO: Support metatypes here const metaType: ReifiedType = { conformances: {}, functions: (functionName) => (innerScope) => member(value, mangleName(functionName).name, innerScope), innerTypes: { Type: () => metaType, }, }; return { conformances: {}, functions: (functionName) => (innerScope) => member(value, mangleName(functionName).name, innerScope), innerTypes: { Type: () => metaType, }, }; } } } export type Value = ExpressionValue | CallableValue | VariableValue | FunctionValue | TupleValue | BoxedValue | StatementsValue | SubscriptValue | CopiedValue | TypeValue | ConformanceValue | OptionalValue | ConditionalValue; export function unbox(value: Value, scope: Scope): VariableValue | SubscriptValue { if (value.kind === "boxed") { return annotateValue(value.contents, value.location); } throw new Error(`Unable to unbox from ${value.kind} value`); } export function typeRequiresBox(type: Value, scope: Scope): Value { return hasRepresentation(type, PossibleRepresentation.All & ~(PossibleRepresentation.Function | PossibleRepresentation.Object | PossibleRepresentation.Symbol | PossibleRepresentation.Array), scope); } export function extractContentOfBox(target: BoxedValue, scope: Scope) { return member(target.contents, 0, scope); } export type UpdateOperator = "=" | "+=" | "-=" | "*=" | "/=" | "|=" | "&="; type Mapped<T extends string | number, U> = { [K in T]: U }; export const binaryOperatorForUpdateOperator: Mapped<Exclude<UpdateOperator, "=">, BinaryOperator> = { "+=": "+", "-=": "-", "*=": "*", "/=": "/", "|=": "|", "&=": "&", }; export const updateOperatorForBinaryOperator: Mapped<"+" | "-" | "*" | "/" | "|" | "&", UpdateOperator> = { "+": "+=", "-": "-=", "*": "*=", "/": "/=", "|": "|=", "&": "&=", }; export function set(dest: Value, source: Value, scope: Scope, operator: UpdateOperator = "=", location?: LocationSource): Value { return transform(source, scope, (sourceExpression: Expression) => { let result: Value; switch (dest.kind) { case "boxed": result = conditional( typeRequiresBox(dest.type, scope), set(extractContentOfBox(dest, scope), expr(sourceExpression), scope, operator, location), set(dest.contents, expr(sourceExpression), scope, operator, location), scope, location, ); break; case "direct": { if (dest.expression.type === "ThisExpression") { throw new Error("Cannot assign to a this expression!"); } if (expressionLiteralValue(sourceExpression) === 1) { if (operator === "+=") { result = expr(updateExpression("++", dest.expression), location); break; } if (operator === "-=") { result = expr(updateExpression("--", dest.expression), location); break; } } result = expr(assignmentExpression(operator, dest.expression, sourceExpression), location); break; } case "subscript": { if (operator !== "=") { result = update(dest, scope, (value) => { return binary(binaryOperatorForUpdateOperator[operator], value, expr(sourceExpression), scope); }, location); } else { // TODO: Populate with correct type result = call(dest.setter, concat(dest.args, [expr(sourceExpression)]), concat(dest.types, [typeValue("Any")]), scope, location); } break; } case "expression": { switch (dest.expression.type) { case "Identifier": case "MemberExpression": result = expr(assignmentExpression(operator, dest.expression, sourceExpression)); break; default: throw new TypeError(`Unable to set an expression with a ${dest.expression.type} value`); } break; } default: { throw new TypeError(`Unable to set a ${dest.kind} value`); } } return statements(ignore(result, scope), location); }); } export function update(dest: Value, scope: Scope, updater: (value: Value) => Value, location?: LocationSource): Value { switch (dest.kind) { case "boxed": return conditional( typeRequiresBox(dest.type, scope), set(extractContentOfBox(dest, scope), updater(extractContentOfBox(dest, scope)), scope, "=", location), set(dest.contents, updater(extractContentOfBox(dest, scope)), scope, "=", location), scope, location, ); case "direct": switch (dest.expression.type) { case "ThisExpression": throw new Error("Cannot update a this expression!"); case "MemberExpression": const memberDest = dest.expression; if (memberDest.object.type !== "Identifier" || (memberDest.computed && typeof expressionLiteralValue(memberDest.property) === "undefined")) { return reuse(expr(dest.expression.object), scope, "object", (object) => { const property = memberDest.property; if (memberDest.computed) { return reuse(expr(property), scope, "property", (reusableProperty) => { return set( member(object, reusableProperty, scope), updater(member(object, reusableProperty, scope)), scope, "=", location, ); }); } if (property.type !== "Identifier") { throw new TypeError(`Expected an Identifier, got a ${property.type}`); } return set( member(object, property.name, scope), updater(member(object, property.name, scope)), scope, "=", location, ); }); } case "Identifier": default: return set(dest, updater(dest), scope, "=", location); } break; case "subscript": // Call the getter, apply the operation, then apply the setter let i = -1; const reusableArgs: Value[] = []; const { args, types, getter, setter } = dest; function iterate(): Value { if (++i < args.length) { return reuse(args[i], scope, "subscript", (argValue) => { reusableArgs.push(argValue); return iterate(); }); } else { const valueFetched = call(getter, reusableArgs, types, scope, location); const result = updater(valueFetched); // TODO: Pass correct type return call(setter, concat(reusableArgs, [result]), concat(types, [typeValue("Any")]), scope, location); } } return iterate(); default: break; } throw new TypeError(`Unable to set a ${dest.kind} value!`); } // TODO: Avoid using dummy types const dummyType = typeValue({ kind: "name", name: "Dummy" }); export function array(values: Value[], scope: Scope, location?: LocationSource) { let prefixStatements: Statement[] = []; const elements: Expression[] = []; for (const value of values.slice().reverse()) { if (value.kind === "statements") { const parsed = parseStatementsValue(value, containsNoReturnStatements); if (typeof parsed !== "undefined") { let newStatements = parsed.statements.slice(); if (typeof parsed.value === "undefined") { elements.unshift(undefinedLiteral); } else if (parsed.value.type === "Identifier") { elements.unshift(parsed.value); } else { const temp = uniqueName(scope, "element"); newStatements = concat(newStatements, [addVariable(scope, temp, dummyType, expr(parsed.value), DeclarationFlags.Const)]); elements.unshift(read(lookup(temp, scope), scope)); } prefixStatements = concat(newStatements, prefixStatements); continue; } } const innerExpression = read(value, scope); if (prefixStatements.length !== 0 && !isPure(innerExpression)) { const temp = uniqueName(scope, "element"); prefixStatements.push(addVariable(scope, temp, dummyType, expr(innerExpression), DeclarationFlags.Const)); elements.unshift(read(lookup(temp, scope), scope)); } else { elements.unshift(innerExpression); } } const expression = annotate(arrayExpression(elements), location); if (prefixStatements.length === 0) { return expr(expression); } prefixStatements.push(annotate(returnStatement(expression), location)); return statements(prefixStatements, location); } export function annotate<T extends Node>(node: T, location?: LocationSource): T { if (typeof location !== "undefined" && (!Object.hasOwnProperty.call(node, "loc") || typeof node.loc === "undefined")) { return Object.assign(Object.create(Object.getPrototypeOf(node)), node, { loc: readLocation(location), }); } return node; } export function annotateValue<T extends Value>(value: T, location?: LocationSource): T { if (typeof location !== "undefined" && (!Object.hasOwnProperty.call(value, "location") || typeof value.location === "undefined")) { return Object.assign(Object.create(Object.getPrototypeOf(value)), value, { location: readLocation(location), }); } return value; } function isExpressionStatement(node: Node): boolean { return node.type === "ExpressionStatement"; } function expressionFromStatement(statement: Statement): Expression { if (statement.type === "ExpressionStatement") { return statement.expression; } throw new TypeError(`Expected expression statment, got a ${statement.type}`); } function parseStatementsValue(value: StatementsValue, allowedStatement: (statement: Statement) => boolean): { statements: Statement[], value?: Expression } | undefined { const body = value.statements; if (body.length === 0) { return { statements: body }; } // Avoid generating an IIFE for statements list const lastStatement = body[body.length - 1]; if (lastStatement.type === "ReturnStatement") { const exceptLast = body.slice(0, body.length - 1); if (exceptLast.every(allowedStatement)) { return lastStatement.argument === null ? { statements: exceptLast } : { statements: exceptLast, value: lastStatement.argument }; } } else if (body.every(allowedStatement)) { return { statements: body }; } return undefined; } interface ContainsNoReturnStatementsState { result: boolean; ignoreCount: number; } const containsNoReturnStatementsHandler = { enter(current: Node, parent: unknown, state: ContainsNoReturnStatementsState) { if (state.ignoreCount === 0 && isReturnStatement(current)) { state.result = true; } if (isFunction(current)) { state.ignoreCount++; } }, exit(current: Node, parent: unknown, state: ContainsNoReturnStatementsState) { if (isFunction(current)) { state.ignoreCount--; } }, }; function containsNoReturnStatements(node: Node): boolean { if (isReturnStatement(node)) { return false; } if (isExpressionStatement(node)) { return true; } const state: ContainsNoReturnStatementsState = { result: true, ignoreCount: 0, }; traverse(node, containsNoReturnStatementsHandler, state); return state.result; } function alternateMethodForKeyInConformance(key: string, target: ProtocolConformance): { name: string, reassign: boolean } | undefined { // Maps += to + and ~= to == when protocol conforms to both const match = key.match(/^(&?[%^&|*+/\-^]|<<|>>)=$/); let name: string; if (match !== null) { name = match[1]; } else if (key === "~=") { name = "=="; } else { return undefined; } return Object.hasOwnProperty.call(target.functions, name) ? { name, reassign: key !== "~=" } : undefined; } function validWitnessTableKeysForConformance(target: ProtocolConformance) { return Object.keys(target.functions).filter((key) => alternateMethodForKeyInConformance(key, target) === undefined).sort(); } function buildRuntimeTypeReference(type: Type, value: Value, scope: Scope) { // Deep-remap types, replacing with a placeholder so that similar type patterns are specialized and a standardized name is generated const substitutionNames: string[] = []; const substitutions: Value[] = []; const stringified = stringifyType(type, (innerType) => { if (innerType.kind === "name") { const result = mappedValueForName(innerType.name, scope); if (typeof result !== "undefined") { substitutionNames.push(innerType.name); substitutions.push(result); return { kind: "name", name: "_", }; } } return innerType; }); const name: string = `:${stringified}.Type`; const mangled = mangleName(name); const globalScope = rootScope(scope); // Emit a type table if one doesn't exist if (!Object.hasOwnProperty.call(globalScope.declarations, name)) { const reified = typeFromValue(value, scope); function typeConformancesObject(innerScope: Scope) { const desiredConformances = Object.keys(reified.conformances); // Find all desired conformances // tslint:disable-next-line:prefer-for-of for (let i = 0; i < desiredConformances.length; i++) { const key = desiredConformances[i]; if (Object.hasOwnProperty.call(reified.conformances, key)) { const current = reified.conformances[key]; for (const requirement of current.requirements) { if (desiredConformances.indexOf(requirement) === -1) { desiredConformances.push(requirement); } } } else { throw new TypeError(`Missing ${key} conformance in ${stringified}`); } } desiredConformances.sort(); // Create a property for each conformance const properties: Array<ObjectMethod | ObjectProperty | SpreadElement> = []; for (const conformanceName of desiredConformances) { const current = reified.conformances[conformanceName]; properties.push(objectProperty(mangleName(conformanceName), objectExpression(validWitnessTableKeysForConformance(current).map((key) => { const scopeName = `${stringified}.${key}`; let requiredArgumentCount: number = 0; const result = current.functions[key](innerScope, (index, argumentName) => { if (index >= requiredArgumentCount) { requiredArgumentCount = index + 1; } return value; }, scopeName, [typeValue("Type")]); if (requiredArgumentCount > 0) { let argumentTypes: Type[] = []; for (let i = 0; i < requiredArgumentCount; i++) { argumentTypes.push({ kind: "name", name: "Any" }); } let resultType: Type; if (result.kind === "callable") { argumentTypes = concat(argumentTypes, result.type.arguments.types); resultType = result.type.return; } else { resultType = { kind: "tuple", types: [], }; } const [args, methodBody] = functionize(innerScope, scopeName, (innerMostScope, arg) => { const repeatedResult = current.functions[key](innerMostScope, (index, argumentName) => { if (index === 0) { return typeValue(type, value.location, arg(0, "Self")); } return arg(index, argumentName); }, scopeName, argumentTypes.map((argumentType) => typeValue(argumentType))); arg(0, "Self"); if (result.kind === "callable") { if (repeatedResult.kind !== "callable") { throw new TypeError(`Expected function to return a callable, instead got a ${result.kind}`); } return repeatedResult.call(innerScope, (index, argumentName) => { return arg(requiredArgumentCount + index, argumentName); }, repeatedResult.type.arguments.types.map((argType) => typeValue(argType))); } return repeatedResult; }, { kind: "function", arguments: { kind: "tuple", types: argumentTypes, }, return: resultType, attributes: [], throws: false, rethrows: false, }); return objectMethod("method", mangleName(key), args, blockStatement(methodBody)); } else if (result.kind === "callable") { const argTypes = result.type.arguments.types.map((argType) => typeValue(argType)); const [args, methodBody] = functionize(innerScope, scopeName, (innerMostScope, arg) => result.call(innerMostScope, arg, argTypes), result.type); return objectMethod("method", mangleName(key), args, blockStatement(methodBody)); } else { return objectProperty(mangleName(key), read(result, innerScope)); } })))); } return objectExpression(properties); } // Placeholder to avoid infinite recursion in tables that are self-referential globalScope.declarations[name] = { flags: DeclarationFlags.Const, declaration: variableDeclaration("const", [variableDeclarator(mangled)]), }; if (substitutions.length === 0) { // Emit direct able globalScope.declarations[name] = { flags: DeclarationFlags.Const, declaration: variableDeclaration("const", [variableDeclarator(mangled, typeConformancesObject(globalScope))]), }; } else { // Emit function that returns a table based on parameters const typeMapping: TypeMap = Object.create(null); const functionized = functionize(globalScope, stringified, (innerScope) => { substitutionNames.forEach((key, i) => { typeMapping[key] = (innerMostScope) => typeFromValue(substitutions[i], innerMostScope); innerScope.mapping[key] = variable(mangleName(key)); }); return expr(typeConformancesObject(innerScope)); }, { kind: "function", arguments: { kind: "tuple", types: substitutions.map(() => typeType), }, return: typeType, throws: false, rethrows: false, attributes: [], }, typeMapping); globalScope.declarations[name] = { flags: DeclarationFlags.Const, declaration: functionDeclaration(mangled, substitutionNames.map(mangleName), blockStatement(functionized[1])), }; } } // Emit reference to table if (substitutions.length === 0) { // Directly as there are no substitutions return mangled; } else { // Parameterized by substitutions return callExpression(mangled, substitutions.map((substitution) => read(substitution, scope))); } } export function read(value: VariableValue, scope: Scope): Identifier | MemberExpression; export function read(value: Value, scope: Scope): Expression; export function read(value: Value, scope: Scope): Expression { switch (value.kind) { case "copied": { const reified = typeFromValue(value.type, scope); if (reified.copy) { return annotate(read(reified.copy(value.value, scope), scope), value.location); } return annotate(read(value.value, scope), value.location); } case "function": { let builder; if (typeof value.parentType === "undefined") { if (Object.hasOwnProperty.call(scope.functions, value.name)) { builder = scope.functions[value.name]; } } else if (value.parentType.kind === "type") { builder = reifyType(value.parentType.type, scope).functions(value.name); } if (typeof builder === "undefined") { throw new Error(`Could not find function to read for ${value.name}`); } const unbound = annotateValue(insertFunction(value.name, scope, builder, value.type), value.location); let func; if (value.substitutions.length) { func = call( member(unbound, "bind", scope), concat([literal(null)], value.substitutions), [], // TODO: Add types for this call expression scope, ); } else { func = unbound; } return annotate(read(func, scope), value.location); } case "tuple": { switch (value.values.length) { case 0: return annotate(undefinedLiteral, value.location); case 1: return annotate(read(value.values[0], scope), value.location); default: return annotate(read(array(value.values, scope), scope), value.location); } } case "expression": { return annotate(value.expression, value.location); } case "callable": { // TODO: Include length to value.call const argTypes = value.type.arguments.types.map((argType) => typeValue(argType)); const [args, body] = functionize(scope, "anonymous", (innerScope, arg) => value.call(innerScope, arg, argTypes), value.type, undefined, value.location); return annotate(functionExpression(undefined, args, annotate(blockStatement(body), value.location)), value.location); } case "direct": { return annotate(value.expression, value.location); } case "statements": { const parsed = parseStatementsValue(value, isExpressionStatement); if (typeof parsed === "undefined") { return annotate(callExpression(annotate(functionExpression(undefined, [], annotate(blockStatement(value.statements), value.location)), value.location), []), value.location); } const result = typeof parsed.value !== "undefined" ? parsed.value : undefinedLiteral; if (parsed.statements.length === 0) { return annotate(result, value.location); } return annotate(sequenceExpression(concat(parsed.statements.map(expressionFromStatement), [result])), value.location); } case "subscript": { return annotate(read(call(value.getter, value.args, value.types, scope, value.location), scope), value.location); } case "boxed": { return annotate(read(conditional( typeRequiresBox(value.type, scope), extractContentOfBox(value, scope), value.contents, scope, value.location, ), scope), value.location); } case "conformance": { return annotate(read(value.type, scope), value.location); } case "type": { // Direct remapping if (typeof value.runtimeValue !== "undefined") { return read(value.runtimeValue, scope); } let type = value.type; while (type.kind === "metatype") { type = type.base; } if (type.kind === "name") { const result = mappedValueForName(type.name, scope); if (typeof result !== "undefined") { return annotate(read(result, scope), value.location); } } return annotate(buildRuntimeTypeReference(type, value, scope), value.location); } case "optional": { const newValue = value.value === undefined ? call(functionValue("Swift.(swift-to-js).emptyOptional()", undefined, "(T.Type) -> T?"), [value.type], [value.type], scope) : call(functionValue("Swift.(swift-to-js).someOptional()", undefined, "(T.Type, T) -> T?"), [value.type, value.value], [value.type, value.type], scope); return read(newValue, scope); } case "conditional": { const predicateExpression = read(value.predicate, scope); const predicateValue = expressionLiteralValue(predicateExpression); if (predicateValue !== undefined) { return annotate(read(predicateValue ? value.consequent : value.alternate, scope), value.location); } return annotate(conditionalExpression( predicateExpression, read(value.consequent, scope), read(value.alternate, scope), ), value.location); } default: { throw new TypeError(`Received an unexpected value of type ${(value as Value).kind}`); } } } function ignoreExpression(expression: Expression | SpreadElement, scope: Scope): Statement[] { outer: switch (expression.type) { case "Identifier": return []; case "SequenceExpression": { let body: Statement[] = []; for (const ignoredExpression of expression.expressions) { if (!isPure(ignoredExpression)) { body = concat(body, ignore(expr(ignoredExpression, expression.loc), scope)); } } return body; } case "BinaryExpression": { let body: Statement[] = []; if (!isPure(expression.left)) { body = concat(body, ignore(expr(expression.left, expression.loc), scope)); } if (!isPure(expression.right)) { body = concat(body, ignore(expr(expression.right, expression.loc), scope)); } return body; } case "UnaryExpression": { switch (expression.operator) { case "!": case "+": case "-": case "~": case "typeof": if (isPure(expression.argument)) { return []; } else { return ignore(expr(expression.argument, expression.loc), scope); } break; default: break; } break; } case "ArrayExpression": { let body: Statement[] = []; for (const ignoredExpression of expression.elements) { if (ignoredExpression === null || ignoredExpression.type != null) { break outer; } body = concat(body, ignore(expr(ignoredExpression, expression.loc), scope)); } return body; } case "ObjectExpression": { let body: Statement[] = []; for (const prop of expression.properties) { if (prop.type !== "ObjectProperty") { break outer; } if (prop.computed && !isPure(prop.key)) { body = concat(body, ignore(expr(prop.key, expression.loc), scope)); } if (!isPure(prop.value)) { if (isExpression(prop.value)) { body = concat(body, ignore(expr(prop.value, expression.loc), scope)); } else { break outer; } } } return body; } case "ConditionalExpression": { return [annotate(ifStatement( expression.test, blockStatement(ignoreExpression(expression.consequent, scope)), blockStatement(ignoreExpression(expression.alternate, scope)), ), expression.loc)]; } case "ArrayExpression": { return expression.elements.reduce((existing, element) => element === null ? existing : concat(existing, ignoreExpression(element, scope)), [] as Statement[]); } case "SpreadElement": { return ignoreExpression(expression.argument, scope); } case "AssignmentExpression": { if (expression.left.type === "Identifier" && expression.right.type === "Identifier" && expression.left.name === expression.right.name) { return []; } break; } default: if (isLiteral(expression)) { return []; } break; } return [annotate(expressionStatement(expression), expression.loc)]; } export function ignore(value: Value, scope: Scope): Statement[] { const transformed = transform(value, scope, expr); switch (transformed.kind) { case "statements": const parsed = parseStatementsValue(transformed, containsNoReturnStatements); if (typeof parsed !== "undefined") { const head = parsed.statements.map((statement) => annotate(statement, value.location)); if (typeof parsed.value !== "undefined" && !isPure(parsed.value)) { return concat(head, [annotate(expressionStatement(parsed.value), value.location)]); } else { return head; } } break; case "expression": return ignoreExpression(annotate(transformed.expression, value.location), scope); case "optional": if (transformed.value === undefined) { return []; } return ignore(transformed.value, scope); case "direct": return []; default: break; } return ignoreExpression(annotate(read(transformed, scope), value.location), scope); } export const undefinedLiteral = identifier("undefined"); export const undefinedValue = expr(undefinedLiteral); export const typeType: Type = { kind: "name", name: "Type" }; export const typeTypeValue = typeValue(typeType); export function transform(value: Value, scope: Scope, callback: (expression: Expression) => Value): Value { for (;;) { if (value.kind === "tuple" && value.values.length > 1) { value = array(value.values, scope, value.location); } else if (value.kind === "subscript") { value = call(value.getter, value.args, value.types, scope, value.location); } else { break; } } if (value.kind === "optional" && value.value !== undefined) { const type = value.type; return transform(value.value, scope, (expression) => callback(read(optional(type, expr(expression), value.location), scope))); } if (value.kind === "statements") { // TODO: Disallow return statements nested inside other statements const parsed = parseStatementsValue(value, containsNoReturnStatements); if (typeof parsed !== "undefined") { const tail = annotateValue(callback(typeof parsed.value !== "undefined" ? parsed.value : annotate(undefinedLiteral, value.location)), value.location); if (tail.kind === "statements") { const parsedTail = parseStatementsValue(tail, containsNoReturnStatements); if (typeof parsedTail !== "undefined" && typeof parsedTail.value !== "undefined" && parsedTail.value.type === "Identifier" && parsedTail.value.name === "undefined") { return statements(concat( parsed.statements, parsedTail.statements, ), tail.location || value.location); } return statements(concat( parsed.statements, tail.statements, ), tail.location || value.location); } if (tail.kind === "direct" && tail.expression.type === "Identifier" && tail.expression.name === "undefined") { return statements(parsed.statements, tail.location || value.location); } return statements(concat( parsed.statements, [annotate(returnStatement(simplifyExpression(read(tail, scope))), tail.location || value.location)], ), tail.location || value.location); } } return annotateValue(callback(simplifyExpression(read(value, scope))), value.location); } export function call(target: Value, args: ReadonlyArray<Value>, argTypes: Array<Value | string>, scope: Scope, location?: LocationSource): Value { const getter: ArgGetter = (i) => { if (i < 0) { throw new RangeError(`Asked for a negative argument index`); } if (i >= args.length) { throw new RangeError(`${stringifyValue(target)} asked for argument ${i + 1}, but only ${args.length} arguments provided`); } return args[i]; }; if (args.length !== argTypes.length) { throw new RangeError(`Expected arguments and argument types to have the same length`); } switch (target.kind) { case "function": if (target.substitutions.length !== 0) { // Type substitutions are passed as prefix arguments args = concat(target.substitutions, args); argTypes = concat(target.substitutions.map((): Value | string => typeTypeValue), argTypes); } let fn; if (typeof target.parentType === "undefined") { // Global functions fn = lookupForMap(scope.functions)(target.name); if (typeof fn === "undefined") { throw new Error(`Could not find function to call for ${target.name}`); } } else if (target.parentType.kind === "type" || target.parentType.kind === "conformance") { const parentType = target.parentType; const reified = typeFromValue(parentType, scope); // Member functions fn = reified.functions(target.name); if (typeof fn === "undefined") { throw new Error(`${stringifyValue(parentType)} does not have a ${target.name} function`); } } else { // Function from a vtable at runtime const func = memberExpression(read(target.parentType, scope), mangleName(target.name)); return call(expr(func, target.location), args, argTypes, scope, location); } return annotateValue(fn(scope, getter, target.name, argTypes.map((argumentType) => typeof argumentType === "string" ? typeValue(argumentType) : argumentType)), location); case "callable": // Inlining is responsible for making the codegen even remotely sane // return call(expr(read(target, scope)), args, scope, location); return annotateValue(target.call(scope, getter, argTypes.map((argumentType) => typeof argumentType === "string" ? typeValue(argumentType) : argumentType)), location); default: break; } if (argTypes.length !== args.length) { throw new RangeError(`Expected the number argument types to be the same as the number of arguments`); } return transform(target, scope, (targetExpression) => { const argExpressions: Expression[] = []; for (let i = 0; i < args.length; i++) { const argType = argTypes[i]; const innerType = typeof argType === "string" ? typeValue(parseType(argType)) : argType; argExpressions.push(innerType.kind === "type" && innerType.type.kind === "modified" && innerType.type.modifier === "inout" ? read(unbox(args[i], scope), scope) : read(args[i], scope)); } return expr(callExpression(targetExpression, argExpressions), location); }); } export function isPure(expression: Expression | PatternLike | SpreadElement): boolean { switch (expression.type) { case "Identifier": case "StringLiteral": case "BooleanLiteral": case "NumericLiteral": case "NullLiteral": case "RegExpLiteral": case "ThisExpression": return true; case "MemberExpression": return isPure(expression.object) && expression.object.type !== "Identifier" && expression.object.type !== "MemberExpression" && expression.object.type !== "ThisExpression" && (!expression.computed || isPure(expression.property)); case "ArrayExpression": for (const element of expression.elements) { if (element !== null) { if (element.type === "SpreadElement" || !isPure(element)) { return false; } } } return true; case "ObjectExpression": for (const prop of expression.properties) { if (prop.type !== "ObjectProperty" || !isPure(prop.value) || (prop.computed && !isPure(prop.key))) { return false; } } return true; default: return false; } } function returnsInt32(expression: Expression): Boolean { switch (expression.type) { case "UnaryExpression": return expression.operator === "~"; case "BinaryExpression": switch (expression.operator) { case ">>": case "<<": case "|": case "&": case "^": return true; default: return false; } default: return false; } } function simplifyExpression(expression: Expression): Expression; function simplifyExpression(expression: Expression | PatternLike): Expression | PatternLike; function simplifyExpression(expression: Expression | PatternLike | SpreadElement): Expression | PatternLike | SpreadElement; function simplifyExpression(expression: Expression | PatternLike | SpreadElement): Expression | PatternLike | SpreadElement { switch (expression.type) { case "ArrayExpression": { return annotate(arrayExpression(expression.elements.map((element) => { if (element !== null && isExpression(element)) { return simplifyExpression(element); } else { return element; } })), expression.loc); } case "ObjectExpression": { return annotate(objectExpression(expression.properties.map((prop) => { if (prop.type === "ObjectProperty") { if (prop.computed) { return annotate(objectProperty(simplifyExpression(prop.key), simplifyExpression(prop.value), true), prop.loc); } else { return annotate(objectProperty(prop.key, simplifyExpression(prop.value)), prop.loc); } } else { return prop; } })), expression.loc); } case "ConditionalExpression": { const testValue = expressionLiteralValue(expression.test); if (typeof testValue !== "undefined") { return annotate(simplifyExpression(testValue ? expression.consequent : expression.alternate), expression.loc); } return annotate(conditionalExpression(simplifyExpression(expression.test), simplifyExpression(expression.consequent), simplifyExpression(expression.alternate)), expression.loc); } case "LogicalExpression": { const left = simplifyExpression(expression.left); const leftValue = expressionLiteralValue(left); const right = simplifyExpression(expression.right); const rightValue = expressionLiteralValue(right); if (expression.operator === "&&") { if (typeof leftValue !== "undefined") { return annotate(leftValue ? right : left, expression.loc); } if (rightValue === true && left.type === "BinaryExpression") { switch (left.operator) { case "==": case "!=": case "===": case "!==": case "<": case "<=": case ">": case ">=": return annotate(left, expression.loc); break; default: break; } } } else if (expression.operator === "||") { if (typeof leftValue !== "undefined") { return annotate(leftValue ? left : right, expression.loc); } } return annotate(logicalExpression(expression.operator, left, right), expression.loc); } case "BinaryExpression": { const value = expressionLiteralValue(expression); if (typeof value !== "undefined") { return literal(value, expression.loc).expression; } if (expression.operator === "|") { if (expression.right.type === "NumericLiteral" && expression.right.value === 0 && returnsInt32(expression.left)) { return annotate(expression.left, expression.loc); } if (expression.left.type === "NumericLiteral" && expression.left.value === 0 && returnsInt32(expression.right)) { return annotate(expression.right, expression.loc); } } return annotate(binaryExpression(expression.operator, simplifyExpression(expression.left), simplifyExpression(expression.right)), expression.loc); } case "UnaryExpression": { const value = expressionLiteralValue(expression); if (typeof value !== "undefined") { return literal(value, expression.loc).expression; } switch (expression.argument.type) { case "LogicalExpression": switch (expression.argument.operator) { case "||": return simplifyExpression(annotate(logicalExpression( "&&", annotate(unaryExpression("!", expression.argument.left), expression.loc), annotate(unaryExpression("!", expression.argument.right), expression.loc), ), expression.loc)); case "&&": return simplifyExpression(annotate(logicalExpression( "||", annotate(unaryExpression("!", expression.argument.left), expression.loc), annotate(unaryExpression("!", expression.argument.right), expression.loc), ), expression.loc)); } break; case "BinaryExpression": { let newOperator: "==" | "!=" | "===" | "!==" | undefined; // Comparison operators can't be inverted because of NaN values switch (expression.argument.operator) { case "==": newOperator = "!="; break; case "!=": newOperator = "=="; break; case "===": newOperator = "!=="; break; case "!==": newOperator = "==="; break; } if (typeof newOperator !== "undefined") { return simplifyExpression(annotate(binaryExpression(newOperator, expression.argument.left, expression.argument.right), expression.loc)); } break; } } return annotate(unaryExpression(expression.operator, simplifyExpression(expression.argument)), expression.loc); } case "MemberExpression": { const value = expressionLiteralValue(expression); if (typeof value !== "undefined") { return literal(value, expression.loc).expression; } if (!expression.computed && expression.property.type === "Identifier") { const objectValue = expressionLiteralValue(expression.object); if (typeof objectValue === "object" && !Array.isArray(objectValue) && objectValue !== null && Object.hasOwnProperty.call(objectValue, expression.property.name)) { const propertyValue = (objectValue as LiteralMap)[expression.property.name]; if (typeof propertyValue === "boolean" || typeof propertyValue === "number" || typeof propertyValue === "string" || typeof propertyValue === "object") { return literal(propertyValue, expression.loc).expression; } } else { return annotate(memberExpression(simplifyExpression(expression.object), expression.property), expression.loc); } } else if (expression.computed) { return annotate(memberExpression(simplifyExpression(expression.object), simplifyExpression(expression.property), true), expression.loc); } break; } case "SequenceExpression": { const oldExpressions = expression.expressions; if (oldExpressions.length === 0) { return annotate(undefinedLiteral, expression.loc); } const newExpressions: Expression[] = []; for (let i = 0; i < oldExpressions.length - 1; i++) { const simplified = simplifyExpression(oldExpressions[i]); if (simplified.type === "SequenceExpression" && isPure(simplified.expressions[simplified.expressions.length - 1])) { for (const element of simplified.expressions) { if (!isPure(element)) { newExpressions.push(element); } } } else if (!isPure(simplified)) { newExpressions.push(simplified); } } if (newExpressions.length === 0) { return simplifyExpression(oldExpressions[oldExpressions.length - 1]); } else { newExpressions.push(simplifyExpression(oldExpressions[oldExpressions.length - 1])); if (newExpressions.length === 1) { return annotate(newExpressions[0], expression.loc); } return annotate(sequenceExpression(newExpressions), expression.loc); } } default: { break; } } return expression; } export function expressionLiteralValue(expression: Expression | Node): LiteralValue | undefined { switch (expression.type) { case "BooleanLiteral": case "NumericLiteral": case "StringLiteral": return expression.value; case "NullLiteral": return null; case "UnaryExpression": { const value = expressionLiteralValue(expression.argument); if (typeof value !== "undefined") { switch (expression.operator) { case "!": return !value; case "-": return -(value as number); case "+": return -(value as number); case "~": return ~(value as number); case "typeof": return typeof value; case "void": return undefined; default: break; } } break; } case "LogicalExpression": case "BinaryExpression": { const left = expressionLiteralValue(expression.left); if (typeof left !== "undefined") { const right = expressionLiteralValue(expression.right); if (typeof right !== "undefined") { switch (expression.operator) { case "&&": return left && right; case "||": return left || right; case "+": return (left as number) + (right as number); case "-": return (left as number) - (right as number); case "*": return (left as number) * (right as number); case "/": return (left as number) / (right as number); case "%": return (left as number) % (right as number); case "**": return (left as number) ** (right as number); case "&": return (left as number) & (right as number); case "|": return (left as number) | (right as number); case ">>": return (left as number) >> (right as number); case ">>>": return (left as number) >>> (right as number); case "<<": return (left as number) << (right as number); case "^": return (left as number) ^ (right as number); case "==": // tslint:disable-next-line:triple-equals return left == right; case "===": return left === right; case "!=": // tslint:disable-next-line:triple-equals return left != right; case "!==": return left !== right; case "<": return (left as number) < (right as number); case "<=": return (left as number) <= (right as number); case "<": return (left as number) > (right as number); case ">=": return (left as number) >= (right as number); default: break; } } } break; } case "ConditionalExpression": { const test = expressionLiteralValue(expression.test); if (typeof test !== "undefined") { return expressionLiteralValue(test ? expression.consequent : expression.alternate); } break; } case "SequenceExpression": { for (const ignoredExpression of expression.expressions.slice(expression.expressions.length - 1)) { if (typeof expressionLiteralValue(ignoredExpression) === "undefined") { return undefined; } } return expressionLiteralValue(expression.expressions[expression.expressions.length - 1]); } case "ArrayExpression": { const result: LiteralValue[] = []; for (const element of expression.elements) { if (element === null || element.type === "SpreadElement") { return undefined; } const elementValue = expressionLiteralValue(element); if (typeof elementValue === "undefined") { return undefined; } result.push(elementValue); } return result; } case "ObjectExpression": { const result: { [name: string]: LiteralValue } = Object.create(null); for (const prop of expression.properties) { if (prop.type !== "ObjectProperty") { return undefined; } const value = expressionLiteralValue(prop.value); if (typeof value === "undefined") { return undefined; } let key: string; if (prop.computed) { const keyValue = expressionLiteralValue(prop.key); if (typeof keyValue !== "string") { return undefined; } key = keyValue; } else { if (prop.key.type !== "Identifier") { return undefined; } key = prop.key.name; } result[key] = value; } return result; } default: break; } return undefined; } interface LiteralMap { readonly [name: string]: LiteralValue; } interface LiteralArray extends ReadonlyArray<LiteralValue> { } type LiteralValue = boolean | number | string | null | LiteralArray | LiteralMap; export function literal(value: LiteralValue, location?: LocationSource): ExpressionValue | VariableValue { if (typeof value === "boolean") { return expr(booleanLiteral(value), location); } else if (typeof value === "number") { return expr(numericLiteral(value), location); } else if (typeof value === "string") { return expr(stringLiteral(value), location); } else if (value === null) { return expr(nullLiteral(), location); } else if (Array.isArray(value)) { return expr(arrayExpression(value.map((element) => literal(element, location).expression)), location); } else if (typeof value === "object") { return expr(objectExpression(Object.keys(value).map((key) => { const expression = literal((value as LiteralMap)[key], location).expression; if (validIdentifier.test(key)) { return objectProperty(identifier(key), expression); } else { // Case where key is not a valid identifier return objectProperty(stringLiteral(key), expression, true); } })), location) as ExpressionValue; } else { throw new TypeError(`Expected to receive a valid literal type, instead got ${typeof value}`); } } export function reuse(value: Value, scope: Scope, uniqueNamePrefix: string, callback: (reusableValue: ExpressionValue | MappedNameValue, literalValue: LiteralValue | undefined) => Value): Value { if (value.kind === "direct") { return callback(value, expressionLiteralValue(value.expression)); } return transform(value, scope, (expression) => { if (isPure(expression) || expression.type === "Identifier") { return callback(expr(expression, value.location), expressionLiteralValue(expression)); } let head: Statement[]; let temp: ExpressionValue | MappedNameValue; if (expression.type === "MemberExpression") { head = []; let object: Expression = expression.object; if (!isPure(object) && object.type !== "Identifier") { const tempName = uniqueName(scope, uniqueNamePrefix); head.push(annotate(addVariable(scope, tempName, "Any", expr(object), DeclarationFlags.Const), value.location)); object = mangleName(tempName); } if (expression.computed) { let property: Expression = expression.property; if (!isPure(property) && property.type !== "Identifier") { const tempName = uniqueName(scope, uniqueNamePrefix); head.push(annotate(addVariable(scope, tempName, "Any", expr(property), DeclarationFlags.Const), value.location)); property = mangleName(tempName); } temp = variable(memberExpression(object, property, true)); } else { temp = variable(memberExpression(object, expression.property, false)); } } else { const tempName = uniqueName(scope, uniqueNamePrefix); head = [annotate(addVariable(scope, tempName, "Any", expr(expression), DeclarationFlags.Const), value.location)]; temp = lookup(tempName, scope); } const tail = callback(annotateValue(temp, value.location), undefined); if (head.length === 0) { return tail; } if (tail.kind === "statements") { return statements(concat(head, tail.statements)); } else { return statements(concat(head, [annotate(returnStatement(read(tail, scope)), tail.location)])); } }); } function passthrough(type: Type) { return type; } export function stringifyType(type: Type, replacer: (type: Type) => Type = passthrough): string { type = replacer(type); switch (type.kind) { case "optional": return stringifyType(type.type, replacer) + "?"; case "generic": if (type.base.kind === "function") { return "<" + type.arguments.map((innerType) => stringifyType(innerType, replacer)).join(", ") + "> " + stringifyType(type.base, replacer); } else { return stringifyType(type.base, replacer) + "<" + type.arguments.map((innerType) => stringifyType(innerType, replacer)).join(", ") + ">"; } case "function": // TODO: Handle attributes return stringifyType(type.arguments, replacer) + (type.throws ? " throws" : "") + (type.rethrows ? " rethrows" : "") + " -> " + stringifyType(type.return, replacer); case "tuple": return "(" + type.types.map((innerType) => stringifyType(innerType, replacer)).join(", ") + ")"; case "array": return "[" + stringifyType(type.type, replacer) + "]"; case "dictionary": return "[" + stringifyType(type.keyType, replacer) + ": " + stringifyType(type.valueType, replacer) + "]"; case "metatype": return stringifyType(type.base, replacer) + "." + type.as; case "modified": return type.modifier + " " + stringifyType(type.type, replacer); case "namespaced": return stringifyType(type.namespace, replacer) + "." + stringifyType(type.type, replacer); case "name": return type.name; case "constrained": return stringifyType(type.type, replacer) + " where " + stringifyType(type.type, replacer) + " : " + stringifyType(type.constraint, replacer); default: throw new TypeError(`Received an unexpected type ${(type as Type).kind}`); } } function stringifyNode(node: Node): string { const result = generate(node, { compact: true, }); return result.code; } export function stringifyValue(value: Value): string { switch (value.kind) { case "copied": { return `copy of ${stringifyValue(value.value)}`; } case "function": { if (typeof value.parentType === "undefined") { return `${value.name} function`; } return `${value.name} function in ${stringifyValue(value.parentType)}`; } case "tuple": { return `(${value.values.map(stringifyValue).join(", ")})`; } case "direct": case "expression": { return `${stringifyNode(value.expression)} (${value.kind})`; } case "callable": { return `anonymous ${stringifyType(value.type)} function`; } case "statements": { return `${stringifyNode(blockStatement(value.statements))} (${value.kind})`; } case "type": { return `${stringifyType(value.type)} (as type)`; } case "conformance": { return `${value.conformance} conformance of ${stringifyValue(value.type)}`; } case "optional": { if (value.value === undefined) { return `empty ${stringifyValue(value.type)}`; } return `wrapped ${stringifyValue(value.value)} (as ${stringifyValue(value.type)})`; } case "boxed": case "subscript": default: { return value.kind; } } } export function representationsForTypeValue(type: Value, scope: Scope): Value { const repFunction = call(functionValue(":rep", conformance(type, "Object", scope), "(Type) -> Int"), [type], ["Type"], scope); return call(repFunction, [], [], scope); } export function hasRepresentation(type: Value, representation: PossibleRepresentation | Value, scope: Scope): Value { return binary("!==", binary("&", representationsForTypeValue(type, scope), typeof representation === "object" ? representation : literal(representation), scope, ), literal(0), scope, ); } export function typeIsDirectlyComparable(type: Value, scope: Scope): boolean { const representations = expressionLiteralValue(read(representationsForTypeValue(type, scope), scope)); return typeof representations === "number" ? (representations & ~(PossibleRepresentation.Boolean | PossibleRepresentation.Number | PossibleRepresentation.String)) === PossibleRepresentation.None : false; }
the_stack
import concat from 'concat-stream'; // @ts-ignore import reproject from 'reproject'; import PolyToLine from '@turf/polygon-to-line'; import Simplify from '@turf/simplify'; import proj4 from 'proj4'; import { Geometry } from 'geojson'; import { FeatureDao } from '../../features/user/featureDao'; import { TileBoundingBoxUtils } from '../tileBoundingBoxUtils'; import { BoundingBox } from '../../boundingBox'; import { ImageUtils } from '../imageUtils'; import { IconCache } from '../../extension/style/iconCache'; import { GeometryCache } from './geometryCache'; import { FeatureDrawType } from './featureDrawType'; import { FeaturePaintCache } from './featurePaintCache'; import { Paint } from './paint'; import { FeatureTableStyles } from '../../extension/style/featureTableStyles'; import { GeoPackage } from '../../geoPackage'; import { FeatureRow } from '../../features/user/featureRow'; import { StyleRow } from '../../extension/style/styleRow'; import { FeatureTilePointIcon } from './featureTilePointIcon'; import { CustomFeaturesTile } from './custom/customFeaturesTile'; import { FeatureStyle } from '../../extension/style/featureStyle'; import { IconRow } from '../../extension/style/iconRow'; import { CrsGeometry } from '../../types/CrsGeometry'; /** * FeatureTiles module. * @module tiles/features */ /** * Tiles drawn from or linked to features. Used to query features and optionally draw tiles * from those features. */ export class FeatureTiles { private static readonly isElectron: boolean = !!( typeof navigator !== 'undefined' && navigator.userAgent.toLowerCase().indexOf(' electron/') > -1 ); private static readonly isNode: boolean = typeof process !== 'undefined' && !!process.version; private static readonly useNodeCanvas: boolean = FeatureTiles.isNode && !FeatureTiles.isElectron; projection: proj4.Converter = null; public simplifyGeometries = true; public compressFormat = 'png'; public pointRadius = 4.0; pointPaint: Paint = new Paint(); public pointIcon: FeatureTilePointIcon = null; linePaint: Paint = new Paint(); private _lineStrokeWidth = 2.0; polygonPaint: Paint = new Paint(); private _polygonStrokeWidth = 2.0; public fillPolygon = true; polygonFillPaint: Paint = new Paint(); featurePaintCache: FeaturePaintCache = new FeaturePaintCache(); geometryCache: GeometryCache = new GeometryCache(); public cacheGeometries = true; iconCache: IconCache = new IconCache(); private _scale = 1.0; geoPackage: GeoPackage; public featureTableStyles: FeatureTableStyles; public maxFeaturesPerTile: number = null; public maxFeaturesTileDraw: CustomFeaturesTile = null; widthOverlap: number; heightOverlap: number; constructor( public featureDao: FeatureDao<FeatureRow>, public tileWidth: number = 256, public tileHeight: number = 256, ) { this.projection = featureDao.projection; this.linePaint.strokeWidth = 2.0; this.polygonPaint.strokeWidth = 2.0; this.polygonFillPaint.color = '#00000011'; this.geoPackage = this.featureDao.geoPackage; if (this.geoPackage != null) { this.featureTableStyles = new FeatureTableStyles(this.geoPackage, featureDao.table); if (!this.featureTableStyles.has()) { this.featureTableStyles = null; } } this.calculateDrawOverlap(); } /** * Manually set the width and height draw overlap * @param {Number} pixels pixels */ set drawOverlap(pixels: number) { this.widthDrawOverlap = pixels; this.heightDrawOverlap = pixels; } /** * Get the width draw overlap * @return {Number} width draw overlap */ get widthDrawOverlap(): number { return this.widthOverlap; } /** * Manually set the width draw overlap * @param {Number} pixels pixels */ set widthDrawOverlap(pixels: number) { this.widthOverlap = pixels; } /** * Get the height draw overlap * @return {Number} height draw overlap */ get heightDrawOverlap(): number { return this.heightOverlap; } /** * Manually set the height draw overlap * @param {Number} pixels pixels */ set heightDrawOverlap(pixels: number) { this.heightOverlap = pixels; } /** * Ignore the feature table styles within the GeoPackage */ ignoreFeatureTableStyles(): void { this.featureTableStyles = null; this.calculateDrawOverlap(); } /** * Clear all caches */ clearCache(): void { this.clearStylePaintCache(); this.clearIconCache(); } /** * Clear the style paint cache */ clearStylePaintCache(): void { this.featurePaintCache.clear(); } /** * Set / resize the style paint cache size * * @param {Number} size * @since 3.3.0 */ set stylePaintCacheSize(size: number) { this.featurePaintCache.resize(size); } /** * Clear the icon cache */ clearIconCache(): void { this.iconCache.clear(); } /** * Set / resize the icon cache size * @param {Number} size new size */ set iconCacheSize(size: number) { this.iconCache.resize(size); } /** * Set the scale * * @param {Number} scale scale factor */ set scale(scale: number) { this._scale = scale; this.linePaint.strokeWidth = scale * this.lineStrokeWidth; this.polygonPaint.strokeWidth = scale * this.polygonStrokeWidth; this.featurePaintCache.clear(); } get scale(): number { return this._scale; } /** * Set geometry cache's max size * @param {Number} maxSize */ set geometryCacheMaxSize(maxSize: number) { this.geometryCache.resize(maxSize); } calculateDrawOverlap(): void { if (this.pointIcon) { this.heightOverlap = this.scale * this.pointIcon.getHeight(); this.widthOverlap = this.scale * this.pointIcon.getWidth(); } else { this.heightOverlap = this.scale * this.pointRadius; this.widthOverlap = this.scale * this.pointRadius; } const lineHalfStroke = (this.scale * this.lineStrokeWidth) / 2.0; this.heightOverlap = Math.max(this.heightOverlap, lineHalfStroke); this.widthOverlap = Math.max(this.widthOverlap, lineHalfStroke); const polygonHalfStroke = (this.scale * this.polygonStrokeWidth) / 2.0; this.heightOverlap = Math.max(this.heightOverlap, polygonHalfStroke); this.widthOverlap = Math.max(this.widthOverlap, polygonHalfStroke); if (this.featureTableStyles !== null && this.featureTableStyles.has()) { let styleRowIds: number[] = []; const tableStyleIds = this.featureTableStyles.getAllTableStyleIds(); if (tableStyleIds !== null) { styleRowIds = styleRowIds.concat(tableStyleIds); } const styleIds = this.featureTableStyles.getAllStyleIds(); if (styleIds != null) { styleRowIds = styleRowIds.concat(styleIds.filter(id => styleRowIds.indexOf(id) === -1)); } const styleDao = this.featureTableStyles.getStyleDao(); for (let i = 0; i < styleRowIds.length; i++) { const styleRowId = styleRowIds[i]; const styleRow = styleDao.queryForId(styleRowId) as StyleRow; const styleHalfWidth = this.scale * (styleRow.getWidthOrDefault() / 2.0); this.widthOverlap = Math.max(this.widthOverlap, styleHalfWidth); this.heightOverlap = Math.max(this.heightOverlap, styleHalfWidth); } let iconRowIds: number[] = []; const tableIconIds = this.featureTableStyles.getAllTableIconIds(); if (tableIconIds != null) { iconRowIds = iconRowIds.concat(tableIconIds); } const iconIds = this.featureTableStyles.getAllIconIds(); if (iconIds != null) { iconRowIds = iconRowIds.concat(iconIds.filter(id => iconRowIds.indexOf(id) === -1)); } const iconDao = this.featureTableStyles.getIconDao(); for (let i = 0; i < iconRowIds.length; i++) { const iconRowId = iconRowIds[i]; const iconRow = iconDao.queryForId(iconRowId) as IconRow; const iconDimensions = iconRow.derivedDimensions; const iconWidth = this.scale * Math.ceil(iconDimensions[0]); const iconHeight = this.scale * Math.ceil(iconDimensions[1]); this.widthOverlap = Math.max(this.widthOverlap, iconWidth); this.heightOverlap = Math.max(this.heightOverlap, iconHeight); } } } set drawOverlapsWithPixels(pixels: number) { this.widthOverlap = pixels; this.heightOverlap = pixels; } getFeatureStyle(featureRow: FeatureRow): FeatureStyle { let featureStyle = null; if (this.featureTableStyles !== null) { featureStyle = this.featureTableStyles.getFeatureStyleForFeatureRow(featureRow); } return featureStyle; } /** * Get the point paint for the feature style, or return the default paint * @param featureStyle feature style * @return paint */ getPointPaint(featureStyle: FeatureStyle): Paint { let paint = this.getFeatureStylePaint(featureStyle, FeatureDrawType.CIRCLE); if (paint == null) { paint = this.pointPaint; } return paint; } /** * Get the line paint for the feature style, or return the default paint * @param featureStyle feature style * @return paint */ getLinePaint(featureStyle: FeatureStyle): Paint { let paint = this.getFeatureStylePaint(featureStyle, FeatureDrawType.STROKE); if (paint === null) { paint = this.linePaint; } return paint; } /** * Get the polygon paint for the feature style, or return the default paint * @param featureStyle feature style * @return paint */ getPolygonPaint(featureStyle: FeatureStyle): Paint { let paint = this.getFeatureStylePaint(featureStyle, FeatureDrawType.STROKE); if (paint == null) { paint = this.polygonPaint; } return paint; } /** * Get the polygon fill paint for the feature style, or return the default * paint * @param featureStyle feature style * @return paint */ getPolygonFillPaint(featureStyle: FeatureStyle): Paint { let paint = null; let hasStyleColor = false; if (featureStyle != null) { const style = featureStyle.style; if (style != null) { if (style.hasFillColor()) { paint = this.getStylePaint(style, FeatureDrawType.FILL); } else { hasStyleColor = style.hasColor(); } } } if (paint === null && !hasStyleColor && this.fillPolygon) { paint = this.polygonFillPaint; } return paint; } /** * Get the feature style paint from cache, or create and cache it * @param featureStyle feature style * @param drawType draw type * @return feature style paint */ getFeatureStylePaint(featureStyle: FeatureStyle, drawType: FeatureDrawType): Paint { let paint = null; if (featureStyle != null) { const style = featureStyle.style; if (style !== null && style.hasColor()) { paint = this.getStylePaint(style, drawType); } } return paint; } /** * Get the style paint from cache, or create and cache it * @param style style row * @param drawType draw type * @return {Paint} paint */ getStylePaint(style: StyleRow, drawType: FeatureDrawType): Paint { let paint = this.featurePaintCache.getPaintForStyleRow(style, drawType); if (paint === undefined || paint === null) { let color = null; let strokeWidth = null; if (drawType === FeatureDrawType.CIRCLE) { color = style.getColor(); } else if (drawType === FeatureDrawType.STROKE) { color = style.getColor(); strokeWidth = this.scale * style.getWidthOrDefault(); } else if (drawType === FeatureDrawType.FILL) { color = style.getFillColor(); strokeWidth = this.scale * style.getWidthOrDefault(); } else { throw new Error('Unsupported Draw Type: ' + drawType); } const stylePaint = new Paint(); stylePaint.color = color; if (strokeWidth !== null) { stylePaint.strokeWidth = strokeWidth; } paint = this.featurePaintCache.getPaintForStyleRow(style, drawType); if (paint === undefined || paint === null) { this.featurePaintCache.setPaintForStyleRow(style, drawType, stylePaint); paint = stylePaint; } } return paint; } /** * Get point color * @return {String} color */ get pointColor(): string { return this.pointPaint.color; } /** * Set point color * @param {String} pointColor point color */ set pointColor(pointColor: string) { this.pointPaint.color = pointColor; } /** * Get line stroke width * @return {Number} width */ get lineStrokeWidth(): number { return this._lineStrokeWidth; } /** * Set line stroke width * @param {Number} lineStrokeWidth line stroke width */ set lineStrokeWidth(lineStrokeWidth: number) { this._lineStrokeWidth = lineStrokeWidth; this.linePaint.strokeWidth = this.scale * this.lineStrokeWidth; } /** * Get line color * @return {String} color */ get lineColor(): string { return this.linePaint.color; } /** * Set line color * @param {String} lineColor line color */ set lineColor(lineColor: string) { this.linePaint.color = lineColor; } /** * Get polygon stroke width * @return {Number} width */ get polygonStrokeWidth(): number { return this._polygonStrokeWidth; } /** * Set polygon stroke width * @param {Number} polygonStrokeWidth polygon stroke width */ set polygonStrokeWidth(polygonStrokeWidth: number) { this._polygonStrokeWidth = polygonStrokeWidth; this.polygonPaint.strokeWidth = this.scale * polygonStrokeWidth; } /** * Get polygon color * @return {String} color */ get polygonColor(): string { return this.polygonPaint.color; } /** * Set polygon color * @param {String} polygonColor polygon color */ set polygonColor(polygonColor: string) { this.polygonPaint.color = polygonColor; } /** * Get polygon fill color * @return {String} color */ get polygonFillColor(): string { return this.polygonFillPaint.color; } /** * Set polygon fill color * @param {String} polygonFillColor polygon fill color */ set polygonFillColor(polygonFillColor: string) { this.polygonFillPaint.color = polygonFillColor; } getFeatureCountXYZ(x: number, y: number, z: number): number { let boundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, z); boundingBox = this.expandBoundingBox(boundingBox); return this.featureDao.countWebMercatorBoundingBox(boundingBox); } async drawTile(x: number, y: number, z: number, canvas: any = null): Promise<any> { const indexed = this.featureDao.isIndexed(); if (indexed) { return this.drawTileQueryIndex(x, y, z, canvas); } else { return this.drawTileQueryAll(x, y, z, canvas); } } async drawTileQueryAll(x: number, y: number, zoom: number, canvas?: any): Promise<any> { let boundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, zoom); boundingBox = this.expandBoundingBox(boundingBox); const count = this.featureDao.getCount(); if (this.maxFeaturesPerTile === null || count <= this.maxFeaturesPerTile) { return this.drawTileWithBoundingBox(boundingBox, zoom, canvas); } else if (this.maxFeaturesTileDraw !== null) { return this.maxFeaturesTileDraw.drawUnindexedTile(256, 256, canvas); } } webMercatorTransform(geoJson: any): any { return reproject.reproject(geoJson, this.projection, proj4('EPSG:3857')); } async drawTileQueryIndex(x: number, y: number, z: number, tileCanvas?: any): Promise<any> { const boundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, z); const expandedBoundingBox = this.expandBoundingBox(boundingBox); const width = 256; const height = 256; const simplifyTolerance = TileBoundingBoxUtils.toleranceDistanceWidthAndHeight(z, width, height); let canvas: any; if (tileCanvas !== null) { canvas = tileCanvas; } if (canvas === undefined || canvas === null) { if (FeatureTiles.useNodeCanvas) { // eslint-disable-next-line @typescript-eslint/no-var-requires const Canvas = require('canvas'); canvas = Canvas.createCanvas(width, height); } else { canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; } } const context = canvas.getContext('2d'); context.clearRect(0, 0, width, height); const tileCount = this.featureDao.countWebMercatorBoundingBox(expandedBoundingBox); if (this.maxFeaturesPerTile === null || tileCount <= this.maxFeaturesPerTile) { const iterator = this.featureDao.fastQueryWebMercatorBoundingBox(expandedBoundingBox); const featureRows = []; for (const featureRow of iterator) { featureRows.push(featureRow); } for (const featureRow of featureRows) { let geojson = null; if (this.cacheGeometries) { geojson = this.geometryCache.getGeometryForFeatureRow(featureRow); } if (geojson === undefined || geojson === null) { geojson = featureRow.geometry.geometry.toGeoJSON() as Geometry & CrsGeometry; this.geometryCache.setGeometry(featureRow.id, geojson); } const style = this.getFeatureStyle(featureRow); try { await this.drawGeometry( simplifyTolerance, geojson, context, this.webMercatorTransform.bind(this), boundingBox, style, ); } catch (e) { console.log('Error drawing geometry', e); } } return new Promise(resolve => { if (FeatureTiles.useNodeCanvas) { const writeStream = concat(function(buffer: Uint8Array | Buffer) { resolve(buffer); }); let stream = null; if (this.compressFormat === 'png') { stream = canvas.createPNGStream(); } else { stream = canvas.createJPEGStream(); } stream.pipe(writeStream); } else { resolve(canvas.toDataURL('image/' + this.compressFormat)); } }); } else if (this.maxFeaturesTileDraw !== null) { // Draw the max features tile return this.maxFeaturesTileDraw.drawTile(width, height, tileCount.toString(), canvas); } } async drawTileWithBoundingBox(boundingBox: BoundingBox, zoom: number, tileCanvas?: any): Promise<any> { const width = 256; const height = 256; const simplifyTolerance = TileBoundingBoxUtils.toleranceDistanceWidthAndHeight(zoom, width, height); let canvas: any; if (tileCanvas !== null) { canvas = tileCanvas; } if (canvas === undefined || canvas === null) { if (FeatureTiles.useNodeCanvas) { // eslint-disable-next-line @typescript-eslint/no-var-requires const Canvas = require('canvas'); canvas = Canvas.createCanvas(width, height); } else { canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; } } const context = canvas.getContext('2d'); context.clearRect(0, 0, width, height); const featureDao = this.featureDao; const each = featureDao.queryForEach(); const featureRows = []; for (const row of each) { featureRows.push(featureDao.getRow(row)); } for (const fr of featureRows) { let gj: Geometry & CrsGeometry = null; if (this.cacheGeometries) { gj = this.geometryCache.getGeometryForFeatureRow(fr); } if (gj === undefined || gj === null) { gj = fr.geometry.geometry.toGeoJSON() as Geometry & CrsGeometry; this.geometryCache.setGeometry(fr.id, gj); } const style = this.getFeatureStyle(fr); try { await this.drawGeometry( simplifyTolerance, gj, context, this.webMercatorTransform.bind(this), boundingBox, style, ); } catch (e) { console.log('Error drawing geometry', e); } } return new Promise(resolve => { if (FeatureTiles.useNodeCanvas) { const writeStream = concat(function(buffer: Uint8Array | Buffer) { resolve(buffer); }); let stream = null; if (this.compressFormat === 'png') { stream = canvas.createPNGStream(); } else { stream = canvas.createJPEGStream(); } stream.pipe(writeStream); } else { resolve(canvas.toDataURL('image/' + this.compressFormat)); } }); } /** * Draw a point in the context * @param geoJson * @param context * @param boundingBox * @param featureStyle * @param transform */ async drawPoint( geoJson: any, context: any, boundingBox: BoundingBox, featureStyle: FeatureStyle, transform: Function, ): Promise<void> { let width: number; let height: number; let iconX: number; let iconY: number; const transformedGeoJson = transform(geoJson); const x = TileBoundingBoxUtils.getXPixel(this.tileWidth, boundingBox, transformedGeoJson.coordinates[0]); const y = TileBoundingBoxUtils.getYPixel(this.tileHeight, boundingBox, transformedGeoJson.coordinates[1]); if (featureStyle !== undefined && featureStyle !== null && featureStyle.hasIcon()) { const iconRow = featureStyle.icon; const image = await this.iconCache.createIcon(iconRow); width = Math.round(this.scale * iconRow.width); height = Math.round(this.scale * iconRow.height); if (x >= 0 - width && x <= this.tileWidth + width && y >= 0 - height && y <= this.tileHeight + height) { const anchorU = iconRow.anchorUOrDefault; const anchorV = iconRow.anchorVOrDefault; iconX = Math.round(x - anchorU * width); iconY = Math.round(y - anchorV * height); context.drawImage(image, iconX, iconY, width, height); } } else if (this.pointIcon !== undefined && this.pointIcon !== null) { width = Math.round(this.scale * this.pointIcon.getWidth()); height = Math.round(this.scale * this.pointIcon.getHeight()); if (x >= 0 - width && x <= this.tileWidth + width && y >= 0 - height && y <= this.tileHeight + height) { iconX = Math.round(x - this.scale * this.pointIcon.getXOffset()); iconY = Math.round(y - this.scale * this.pointIcon.getYOffset()); ImageUtils.scaleBitmap(this.pointIcon.getIcon(), this.scale).then(image => { context.drawImage(image, iconX, iconY, width, height); }); } } else { context.save(); let radius = null; if (featureStyle !== undefined && featureStyle !== null) { const styleRow = featureStyle.style; if (styleRow !== undefined && styleRow !== null) { radius = this.scale * (styleRow.getWidthOrDefault() / 2.0); } } if (radius == null) { radius = this.scale * this.pointRadius; } const pointPaint = this.getPointPaint(featureStyle); if (x >= 0 - radius && x <= this.tileWidth + radius && y >= 0 - radius && y <= this.tileHeight + radius) { const circleX = Math.round(x); const circleY = Math.round(y); context.beginPath(); context.arc(circleX, circleY, radius, 0, 2 * Math.PI, true); context.closePath(); context.fillStyle = pointPaint.colorRGBA; context.fill(); } context.restore(); } } /** * When the simplify tolerance is set, simplify the points to a similar * curve with fewer points. * @param simplifyTolerance simplify tolerance in meters * @param lineString GeoJSON * @return simplified GeoJSON * @since 2.0.0 */ simplifyPoints(simplifyTolerance: number, lineString: any): any | null { let simplifiedGeoJSON = null; const shouldProject = this.projection !== null && this.featureDao.srs.organization_coordsys_id !== 3857; if (this.simplifyGeometries) { try { // Reproject to web mercator if not in meters if (shouldProject) { lineString = reproject.reproject(lineString, this.projection, proj4('EPSG:3857')); } simplifiedGeoJSON = Simplify(lineString, { tolerance: simplifyTolerance, highQuality: false, mutate: false, }); // Reproject back to the original projection if (shouldProject) { simplifiedGeoJSON = reproject.reproject(simplifiedGeoJSON, proj4('EPSG:3857'), this.projection); } } catch (e) { // This could happen if the linestring contains any empty points [NaN, NaN] console.log('Unable to simplify geometry', e); } } else { simplifiedGeoJSON = lineString; } return simplifiedGeoJSON; } /** * Get the path of the line string * @param simplifyTolerance simplify tolerance in meters * @param transform * @param lineString * @param context * @param boundingBox */ getPath( simplifyTolerance: number, lineString: any, transform: Function, context: any, boundingBox: BoundingBox, ): void { const simplifiedLineString = transform(this.simplifyPoints(simplifyTolerance, lineString)); if (simplifiedLineString.coordinates.length > 0) { let coordinate = simplifiedLineString.coordinates[0]; let x = TileBoundingBoxUtils.getXPixel(this.tileWidth, boundingBox, coordinate[0]); let y = TileBoundingBoxUtils.getYPixel(this.tileHeight, boundingBox, coordinate[1]); context.moveTo(x, y); for (let i = 1; i < simplifiedLineString.coordinates.length; i++) { coordinate = simplifiedLineString.coordinates[i]; x = TileBoundingBoxUtils.getXPixel(this.tileWidth, boundingBox, coordinate[0]); y = TileBoundingBoxUtils.getYPixel(this.tileHeight, boundingBox, coordinate[1]); context.lineTo(x, y); } } } /** * Draw a line in the context * @param simplifyTolerance * @param geoJson * @param context * @param featureStyle * @param transform * @param boundingBox */ drawLine( simplifyTolerance: number, geoJson: any, context: any, featureStyle: FeatureStyle, transform: Function, boundingBox: BoundingBox, ): void { context.save(); context.beginPath(); const paint = this.getLinePaint(featureStyle); context.strokeStyle = paint.colorRGBA; context.lineWidth = paint.strokeWidth; this.getPath(simplifyTolerance, geoJson, transform, context, boundingBox); context.stroke(); context.closePath(); context.restore(); } /** * Draw a polygon in the context * @param simplifyTolerance * @param geoJson * @param context * @param featureStyle * @param transform * @param boundingBox */ drawPolygon( simplifyTolerance: any, geoJson: any, context: any, featureStyle: FeatureStyle, transform: Function, boundingBox: BoundingBox, ): void { context.save(); context.beginPath(); this.getPath(simplifyTolerance, geoJson, transform, context, boundingBox); context.closePath(); const fillPaint = this.getPolygonFillPaint(featureStyle); if (fillPaint !== undefined && fillPaint !== null) { context.fillStyle = fillPaint.colorRGBA; context.fill(); } const paint = this.getPolygonPaint(featureStyle); context.strokeStyle = paint.colorRGBA; context.lineWidth = paint.strokeWidth; context.stroke(); context.restore(); } /** * Add a feature to the batch * @param simplifyTolerance * @param geoJson * @param context * @param transform * @param boundingBox * @param featureStyle */ async drawGeometry( simplifyTolerance: number, geoJson: Geometry, context: any, transform: Function, boundingBox: BoundingBox, featureStyle: FeatureStyle, ): Promise<void> { let i, lsGeom; if (geoJson.type === 'Point') { await this.drawPoint(geoJson, context, boundingBox, featureStyle, transform); } else if (geoJson.type === 'LineString') { this.drawLine(simplifyTolerance, geoJson, context, featureStyle, transform, boundingBox); } else if (geoJson.type === 'Polygon') { const converted = PolyToLine(geoJson); if (converted.type === 'Feature') { if (converted.geometry.type === 'LineString') { this.drawPolygon(simplifyTolerance, converted.geometry, context, featureStyle, transform, boundingBox); } else if (converted.geometry.type === 'MultiLineString') { for (i = 0; i < converted.geometry.coordinates.length; i++) { lsGeom = { type: 'LineString', coordinates: converted.geometry.coordinates[i], }; this.drawPolygon(simplifyTolerance, lsGeom, context, featureStyle, transform, boundingBox); } } } else { converted.features.forEach(feature => { if (feature.geometry.type === 'LineString') { this.drawPolygon(simplifyTolerance, feature.geometry, context, featureStyle, transform, boundingBox); } else if (feature.geometry.type === 'MultiLineString') { for (i = 0; i < feature.geometry.coordinates.length; i++) { lsGeom = { type: 'LineString', coordinates: feature.geometry.coordinates[i], }; this.drawPolygon(simplifyTolerance, lsGeom, context, featureStyle, transform, boundingBox); } } }); } } else if (geoJson.type === 'MultiPoint') { for (i = 0; i < geoJson.coordinates.length; i++) { await this.drawGeometry( simplifyTolerance, { type: 'Point', coordinates: geoJson.coordinates[i], }, context, transform, boundingBox, featureStyle, ); } } else if (geoJson.type === 'MultiLineString') { for (i = 0; i < geoJson.coordinates.length; i++) { await this.drawGeometry( simplifyTolerance, { type: 'LineString', coordinates: geoJson.coordinates[i], }, context, transform, boundingBox, featureStyle, ); } } else if (geoJson.type === 'MultiPolygon') { for (i = 0; i < geoJson.coordinates.length; i++) { await this.drawGeometry( simplifyTolerance, { type: 'Polygon', coordinates: geoJson.coordinates[i], }, context, transform, boundingBox, featureStyle, ); } } } /** * Create an expanded bounding box to handle features outside the tile that overlap * @param webMercatorBoundingBox web mercator bounding box * @return {BoundingBox} bounding box */ expandBoundingBox(webMercatorBoundingBox: BoundingBox): BoundingBox { return this.expandWebMercatorBoundingBox(webMercatorBoundingBox, webMercatorBoundingBox); } /** * Create an expanded bounding box to handle features outside the tile that overlap * @param webMercatorBoundingBox web mercator bounding box * @param tileWebMercatorBoundingBox tile web mercator bounding box * @return {BoundingBox} bounding box */ expandWebMercatorBoundingBox( webMercatorBoundingBox: BoundingBox, tileWebMercatorBoundingBox: BoundingBox, ): BoundingBox { // Create an expanded bounding box to handle features outside the tile that overlap let minLongitude = TileBoundingBoxUtils.getLongitudeFromPixel( this.tileWidth, webMercatorBoundingBox, tileWebMercatorBoundingBox, 0 - this.widthOverlap, ); let maxLongitude = TileBoundingBoxUtils.getLongitudeFromPixel( this.tileWidth, webMercatorBoundingBox, tileWebMercatorBoundingBox, this.tileWidth + this.widthOverlap, ); let maxLatitude = TileBoundingBoxUtils.getLatitudeFromPixel( this.tileHeight, webMercatorBoundingBox, tileWebMercatorBoundingBox, 0 - this.heightOverlap, ); let minLatitude = TileBoundingBoxUtils.getLatitudeFromPixel( this.tileHeight, webMercatorBoundingBox, tileWebMercatorBoundingBox, this.tileHeight + this.heightOverlap, ); // Choose the most expanded longitudes and latitudes minLongitude = Math.min(minLongitude, webMercatorBoundingBox.minLongitude); maxLongitude = Math.max(maxLongitude, webMercatorBoundingBox.maxLongitude); minLatitude = Math.min(minLatitude, webMercatorBoundingBox.minLatitude); maxLatitude = Math.max(maxLatitude, webMercatorBoundingBox.maxLatitude); // Bound with the web mercator limits minLongitude = Math.max(minLongitude, -1 * TileBoundingBoxUtils.WEB_MERCATOR_HALF_WORLD_WIDTH); maxLongitude = Math.min(maxLongitude, TileBoundingBoxUtils.WEB_MERCATOR_HALF_WORLD_WIDTH); minLatitude = Math.max(minLatitude, -1 * TileBoundingBoxUtils.WEB_MERCATOR_HALF_WORLD_WIDTH); maxLatitude = Math.min(maxLatitude, TileBoundingBoxUtils.WEB_MERCATOR_HALF_WORLD_WIDTH); return new BoundingBox(minLongitude, maxLongitude, minLatitude, maxLatitude); } }
the_stack
import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'; import { IService } from './main'; import { ElectronStateDB } from './state'; import { JSONObject, JSONValue } from '@lumino/coreutils'; import log from 'electron-log'; import { AsyncRemote, asyncRemoteMain } from '../asyncremote'; import { IPythonEnvironment } from './tokens'; import { IRegistry } from './registry'; import fetch from 'node-fetch'; import * as yaml from 'js-yaml'; import * as semver from 'semver'; import * as ejs from 'ejs'; import * as path from 'path'; import * as fs from 'fs'; import { getAppDir, getUserDataDir } from './utils'; import { execFile } from 'child_process'; import { loadingAnimation } from '../assets/svg'; export interface IApplication { /** * Register as service with persistent state. * * @return promise fulfileld with the service's previous state. */ registerStatefulService: (service: IStatefulService) => Promise<JSONValue>; registerClosingService: (service: IClosingService) => void; /** * Force the application service to write data to the disk. */ saveState: (service: IStatefulService, data: JSONValue) => Promise<void>; getPythonEnvironment(): Promise<IPythonEnvironment>; setCondaRootPath(condaRootPath: string): void; getCondaRootPath(): Promise<string>; } /** * A service that has data that needs to persist. */ export interface IStatefulService { /** * The human-readable id for the service state. Must be unique * to each service. */ id: string; /** * Called before the application quits. Qutting will * be suspended until the returned promise is resolved with * the service's state. * * @return promise that is fulfilled with the service's state. */ getStateBeforeQuit(): Promise<JSONValue>; /** * Called before state is passed to the service. Implementing * services should scan the state for issues in this function. * If the data is invalid, the function should return false. * * @return true if the data is valid, false otherwise. */ verifyState: (state: JSONValue) => boolean; } /** * A service that has to complete some task on application exit */ export interface IClosingService { /** * Called before the application exits and after the states are saved. * Service resolves the promise upon a successful cleanup. * * @return promise that is fulfilled when the service is ready to quit */ finished(): Promise<void>; } export namespace IAppRemoteInterface { export let checkForUpdates: AsyncRemote.IMethod<void, void> = { id: 'JupyterLabDesktop-check-for-updates' }; export let openDevTools: AsyncRemote.IMethod<void, void> = { id: 'JupyterLabDesktop-open-dev-tools' }; export let getCurrentPythonEnvironment: AsyncRemote.IMethod< void, IPythonEnvironment > = { id: 'JupyterLabDesktop-get-python-env' }; export let getCurrentRootPath: AsyncRemote.IMethod<void, string> = { id: 'JupyterLabDesktop-get-current-path' }; export let showPythonPathSelector: AsyncRemote.IMethod<void, void> = { id: 'JupyterLabDesktop-select-python-path' }; } export class JupyterApplication implements IApplication, IStatefulService { readonly id = 'JupyterLabDesktop'; private _registry: IRegistry; /** * Construct the Jupyter application */ constructor(registry: IRegistry) { this._registry = registry; this._registerListeners(); // Get application state from state db file. this._appState = new Promise<JSONObject>((res, rej) => { this._appStateDB .fetch(JupyterApplication.APP_STATE_NAMESPACE) .then((state: JSONObject) => { res(state); }) .catch(e => { log.error(e); res({}); }); }); this._applicationState = { checkForUpdatesAutomatically: true, pythonPath: '', condaRootPath: '' }; this.registerStatefulService(this).then( (state: JupyterApplication.IState) => { if (state) { this._applicationState = state; if (this._applicationState.pythonPath === undefined) { this._applicationState.pythonPath = ''; } } const bundledPythonPath = this._registry.getBundledPythonPath(); let pythonPath = this._applicationState.pythonPath; if (pythonPath === '') { pythonPath = bundledPythonPath; } const useBundledPythonPath = pythonPath === bundledPythonPath; if (this._registry.validatePythonEnvironmentAtPath(pythonPath)) { this._registry.setDefaultPythonPath(pythonPath); this._applicationState.pythonPath = pythonPath; } else { this._showPythonSelectorDialog( useBundledPythonPath ? 'invalid-bundled-env' : 'invalid-env' ); } if ( process.platform !== 'darwin' && this._applicationState.checkForUpdatesAutomatically ) { setTimeout(() => { this._checkForUpdates('on-new-version'); }, 5000); } } ); } getPythonEnvironment(): Promise<IPythonEnvironment> { return new Promise<IPythonEnvironment>((resolve, _reject) => { this._appState.then((state: JSONObject) => { resolve(this._registry.getCurrentPythonEnvironment()); }); }); } setCondaRootPath(condaRootPath: string): void { this._applicationState.condaRootPath = condaRootPath; } getCondaRootPath(): Promise<string> { return new Promise<string>((resolve, _reject) => { this._appState.then((state: JSONObject) => { resolve(this._applicationState.condaRootPath); }); }); } registerStatefulService(service: IStatefulService): Promise<JSONValue> { this._services.push(service); return new Promise<JSONValue>((res, rej) => { this._appState .then((state: JSONObject) => { if ( state && state[service.id] && service.verifyState(state[service.id]) ) { res(state[service.id]); } res(null); }) .catch(() => { res(null); }); }); } registerClosingService(service: IClosingService): void { this._closing.push(service); } saveState(service: IStatefulService, data: JSONValue): Promise<void> { this._updateState(service.id, data); return this._saveState(); } getStateBeforeQuit(): Promise<JupyterApplication.IState> { return Promise.resolve(this._applicationState); } verifyState(state: JupyterApplication.IState): boolean { return true; } private _updateState(id: string, data: JSONValue): void { let prevState = this._appState; this._appState = new Promise<JSONObject>((res, rej) => { prevState .then((state: JSONObject) => { state[id] = data; res(state); }) .catch((state: JSONObject) => res(state)); }); } private _rewriteState(ids: string[], data: JSONValue[]): void { let prevState = this._appState; this._appState = new Promise<JSONObject>((res, rej) => { prevState .then(() => { let state: JSONObject = {}; ids.forEach((id: string, idx: number) => { state[id] = data[idx]; }); res(state); }) .catch((state: JSONObject) => res(state)); }); } private _saveState(): Promise<void> { return new Promise<void>((res, rej) => { this._appState .then((state: JSONObject) => { return this._appStateDB.save( JupyterApplication.APP_STATE_NAMESPACE, state ); }) .then(() => { res(); }) .catch(e => { rej(e); }); }); } /** * Register all application event listeners */ private _registerListeners(): void { // On OS X it is common for applications and their menu bar to stay // active until the user quits explicitly with Cmd + Q. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('will-quit', event => { event.preventDefault(); // Collect data from services let state: Promise<JSONValue>[] = this._services.map( (s: IStatefulService) => { return s.getStateBeforeQuit(); } ); let ids: string[] = this._services.map((s: IStatefulService) => { return s.id; }); // Wait for all services to return state Promise.all(state) .then((data: JSONValue[]) => { this._rewriteState(ids, data); return this._saveState(); }) .then(() => { this._quit(); }) .catch(() => { log.error(new Error('JupyterLab did not save state successfully')); this._quit(); }); }); app.on('browser-window-focus', (_event: Event, window: BrowserWindow) => { this._window = window; }); ipcMain.on('set-check-for-updates-automatically', (_event, autoUpdate) => { this._applicationState.checkForUpdatesAutomatically = autoUpdate; }); ipcMain.on('launch-installer-download-page', () => { shell.openExternal( 'https://github.com/jupyterlab/jupyterlab-desktop/releases' ); }); ipcMain.on('select-python-path', event => { const currentEnv = this._registry.getCurrentPythonEnvironment(); dialog .showOpenDialog({ properties: ['openFile', 'showHiddenFiles', 'noResolveAliases'], buttonLabel: 'Use Path', defaultPath: currentEnv ? path.dirname(currentEnv.path) : undefined }) .then(({ filePaths }) => { if (filePaths.length > 0) { event.sender.send('custom-python-path-selected', filePaths[0]); } }); }); ipcMain.on('install-bundled-python-env', event => { const platform = process.platform; const isWin = platform === 'win32'; const appDir = getAppDir(); const appVersion = app.getVersion(); const installerPath = isWin ? `${appDir}\\env_installer\\JupyterLabDesktopAppServer-${appVersion}-Windows-x86_64.exe` : platform === 'darwin' ? `${appDir}/env_installer/JupyterLabDesktopAppServer-${appVersion}-MacOSX-x86_64.sh` : `${appDir}/env_installer/JupyterLabDesktopAppServer-${appVersion}-Linux-x86_64.sh`; const userDataDir = getUserDataDir(); const installPath = path.join(userDataDir, 'jlab_server'); if (fs.existsSync(installPath)) { const choice = dialog.showMessageBoxSync({ type: 'warning', message: 'Do you want to overwrite?', detail: `Install path (${installPath}) is not empty. Would you like to overwrite it?`, buttons: ['Overwrite', 'Cancel'], defaultId: 1, cancelId: 0 }); if (choice === 0) { fs.rmdirSync(installPath, { recursive: true }); } else { event.sender.send('install-bundled-python-env-result', 'CANCELLED'); return; } } const installerProc = execFile(installerPath, ['-b', '-p', installPath], { shell: isWin ? 'cmd.exe' : '/bin/bash', env: { ...process.env } }); installerProc.on('exit', (exitCode: number) => { if (exitCode === 0) { event.sender.send('install-bundled-python-env-result', 'SUCCESS'); app.relaunch(); app.quit(); } else { event.sender.send('install-bundled-python-env-result', 'FAILURE'); log.error(new Error(`Installer Exit: ${exitCode}`)); } }); installerProc.on('error', (err: Error) => { event.sender.send('install-bundled-python-env-result', 'FAILURE'); log.error(err); }); }); ipcMain.handle('validate-python-path', (event, path) => { return this._registry.validatePythonEnvironmentAtPath(path); }); ipcMain.on('show-invalid-python-path-message', (event, path) => { const requirements = this._registry.getRequirements(); const reqVersions = requirements.map( req => `${req.name} ${req.versionRange.format()}` ); const reqList = reqVersions.join(', '); const message = `Failed to find a compatible Python environment at the configured path "${path}". Environment Python package requirements are: ${reqList}.`; dialog.showMessageBox({ message, type: 'error' }); }); ipcMain.on('set-python-path', (event, path) => { this._applicationState.pythonPath = path; app.relaunch(); app.quit(); }); asyncRemoteMain.registerRemoteMethod( IAppRemoteInterface.checkForUpdates, (): Promise<void> => { this._checkForUpdates('always'); return Promise.resolve(); } ); asyncRemoteMain.registerRemoteMethod( IAppRemoteInterface.openDevTools, (): Promise<void> => { this._window.webContents.openDevTools(); return Promise.resolve(); } ); asyncRemoteMain.registerRemoteMethod( IAppRemoteInterface.getCurrentPythonEnvironment, (): Promise<IPythonEnvironment> => { return this.getPythonEnvironment(); } ); asyncRemoteMain.registerRemoteMethod( IAppRemoteInterface.getCurrentRootPath, async (): Promise<string> => { return process.env.JLAB_DESKTOP_HOME || app.getPath('home'); } ); asyncRemoteMain.registerRemoteMethod( IAppRemoteInterface.showPythonPathSelector, (): Promise<void> => { this._showPythonSelectorDialog('change'); return Promise.resolve(); } ); } private _showUpdateDialog( type: 'updates-available' | 'error' | 'no-updates' ) { const dialog = new BrowserWindow({ title: 'JupyterLab Update', width: 400, height: 150, resizable: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); dialog.setMenuBarVisibility(false); const checkForUpdatesAutomatically = this._applicationState.checkForUpdatesAutomatically !== false; const message = type === 'error' ? 'Error occurred while checking for updates!' : type === 'no-updates' ? 'There are no updates available.' : `There is a new version available. Download the latest version from <a href="javascript:void(0)" onclick='handleReleasesLink(this);'>the Releases page</a>.`; const template = ` <body style="background: rgba(238,238,238,1); font-size: 13px; font-family: Helvetica, Arial, sans-serif"> <div style="height: 100%; display: flex;flex-direction: column; justify-content: space-between;"> <div> <%- message %> </div> <div> <label><input type='checkbox' <%= checkForUpdatesAutomatically ? 'checked' : '' %> onclick='handleAutoCheckForUpdates(this);'>Check for updates automatically</label> </div> </div> <script> const ipcRenderer = require('electron').ipcRenderer; function handleAutoCheckForUpdates(el) { ipcRenderer.send('set-check-for-updates-automatically', el.checked); } function handleReleasesLink(el) { ipcRenderer.send('launch-installer-download-page'); } </script> </body> `; const pageSource = ejs.render(template, { message, checkForUpdatesAutomatically }); dialog.loadURL(`data:text/html;charset=utf-8,${pageSource}`); } private _showPythonSelectorDialog( reason: 'change' | 'invalid-bundled-env' | 'invalid-env' = 'change' ) { const dialog = new BrowserWindow({ title: 'Set Python Environment', width: 600, height: 280, resizable: false, parent: this._window, modal: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); dialog.setMenuBarVisibility(false); const bundledPythonPath = this._registry.getBundledPythonPath(); const pythonPath = this._applicationState.pythonPath; let checkBundledPythonPath = false; if ( reason === 'invalid-bundled-env' || pythonPath === '' || pythonPath === bundledPythonPath ) { checkBundledPythonPath = true; } const configuredPath = pythonPath === '' ? bundledPythonPath : pythonPath; const requirements = this._registry.getRequirements(); const reqVersions = requirements.map( req => `${req.name} ${req.versionRange.format()}` ); const reqList = reqVersions.join(', '); const message = reason === 'change' ? `Select the Python executable in the conda or virtualenv environment you would like to use for JupyterLab Desktop. Python packages in the environment selected need to meet the following requirements: ${reqList}. Prebuilt extensions installed in the selected environment will also be available in JupyterLab Desktop.` : ejs.render( `Failed to find a compatible Python environment at the configured path "<%= configuredPath %>". Environment Python package requirements are: ${reqList}.`, { configuredPath } ); const template = ` <html> <body style="background: rgba(238,238,238,1); font-size: 13px; font-family: Helvetica, Arial, sans-serif; padding: 20px;"> <style> .row {display: flex; margin-bottom: 10px;} .progress-message {margin-right: 5px; line-height: 24px; visibility: hidden;} .progress-animation {margin-right: 5px; visibility: hidden;} </style> <div style="height: 100%; display: flex;flex-direction: column; justify-content: space-between;"> <div class="row"> <b>Set Python Environment</b> </div> <div class="row"> ${message} </div> <div> <% if (reason === 'invalid-bundled-env') { %> <div class="row"> <input type="radio" id="install-new" name="env_type" value="install-new" checked %> onchange="handleEnvTypeChange(this);"> <label for="install-new">Install Python environment using the bundled installer</label> </div> <% } else { %> <div class="row"> <input type="radio" id="bundled" name="env_type" value="bundled" <%= checkBundledPythonPath ? 'checked' : '' %> onchange="handleEnvTypeChange(this);"> <label for="bundled">Use the bundled Python environment</label> </div> <% } %> <div class="row"> <input type="radio" id="custom" name="env_type" value="custom" <%= !checkBundledPythonPath ? 'checked' : '' %> onchange="handleEnvTypeChange(this);"> <label for="custom">Use a custom Python environment</label> </div> <div class="row"> <div style="flex-grow: 1;"> <input type="text" id="python-path" value="<%= pythonPath %>" readonly style="width: 100%;"></input> </div> <div> <button id='select-python-path' onclick='handleSelectPythonPath(this);'>Select Python path</button> </div> </div> <div class="row" style="justify-content: flex-end;"> <div id="progress-message" class="progress-message"></div> <div id="progress-animation" class="progress-animation">${loadingAnimation}</div> <button id="apply" onclick='handleApply(this);' style='margin-right: 5px;'>Apply and restart</button> <button id="cancel" onclick='handleCancel(this);'>Cancel</button> </div> </div> </div> <script> const ipcRenderer = require('electron').ipcRenderer; let pythonPath = ''; const installNewRadio = document.getElementById('install-new'); const bundledRadio = document.getElementById('bundled'); const pythonPathInput = document.getElementById('python-path'); const selectPythonPathButton = document.getElementById('select-python-path'); const applyButton = document.getElementById('apply'); const cancelButton = document.getElementById('cancel'); const progressMessage = document.getElementById('progress-message'); const progressAnimation = document.getElementById('progress-animation'); function handleSelectPythonPath(el) { ipcRenderer.send('select-python-path'); } function handleEnvTypeChange() { const installNewOrUseBundled = (installNewRadio && installNewRadio.checked) || (bundledRadio && bundledRadio.checked); pythonPathInput.disabled = installNewOrUseBundled; selectPythonPathButton.disabled = installNewOrUseBundled; } function showProgress(message, animate) { progressMessage.innerText = message; progressMessage.style.visibility = message !== '' ? 'visible' : 'hidden'; progressAnimation.style.visibility = animate ? 'visible' : 'hidden'; } function handleApply(el) { if (installNewRadio && installNewRadio.checked) { ipcRenderer.send('install-bundled-python-env'); showProgress('Installing environment', true); applyButton.disabled = true; cancelButton.disabled = true; } else if (bundledRadio && bundledRadio.checked) { ipcRenderer.send('set-python-path', ''); } else { ipcRenderer.invoke('validate-python-path', pythonPathInput.value).then((valid) => { if (valid) { ipcRenderer.send('set-python-path', pythonPathInput.value); } else { ipcRenderer.send('show-invalid-python-path-message', pythonPathInput.value); } }); } } function handleCancel(el) { window.close(); } ipcRenderer.on('custom-python-path-selected', (event, path) => { pythonPathInput.value = path; }); ipcRenderer.on('install-bundled-python-env-result', (event, result) => { const message = result === 'CANCELLED' ? 'Installation cancelled!' : result === 'FAILURE' ? 'Failed to install the environment!' : ''; showProgress(message, false); const disableButtons = result === 'SUCCESS'; applyButton.disabled = disableButtons; cancelButton.disabled = disableButtons; }); handleEnvTypeChange(); </script> </body> </html> `; const pageSource = ejs.render(template, { reason, checkBundledPythonPath, pythonPath }); dialog.loadURL(`data:text/html;charset=utf-8,${pageSource}`); } private _checkForUpdates(showDialog: 'on-new-version' | 'always') { fetch( 'https://github.com/jupyterlab/jupyterlab-desktop/releases/latest/download/latest.yml' ) .then(async response => { try { const data = await response.text(); const latestReleaseData = yaml.load(data); const latestVersion = (latestReleaseData as any).version; const currentVersion = app.getVersion(); const newVersionAvailable = semver.compare(currentVersion, latestVersion) === -1; if (showDialog === 'always' || newVersionAvailable) { this._showUpdateDialog( newVersionAvailable ? 'updates-available' : 'no-updates' ); } } catch (error) { if (showDialog === 'always') { this._showUpdateDialog('error'); } console.error('Failed to check for updates:', error); } }) .catch(error => { if (showDialog === 'always') { this._showUpdateDialog('error'); } console.error('Failed to check for updates:', error); }); } private _quit(): void { let closing: Promise<void>[] = this._closing.map((s: IClosingService) => { return s.finished(); }); Promise.all(closing) .then(() => { process.exit(); }) .catch(err => { log.error(new Error('JupyterLab could not close successfully')); process.exit(); }); } private _appStateDB = new ElectronStateDB({ namespace: 'jupyterlab-desktop-data' }); private _appState: Promise<JSONObject>; private _applicationState: JupyterApplication.IState; private _services: IStatefulService[] = []; private _closing: IClosingService[] = []; /** * The most recently focused window */ private _window: Electron.BrowserWindow; } export namespace JupyterApplication { export const APP_STATE_NAMESPACE = 'jupyterlab-desktop'; export interface IState extends JSONObject { checkForUpdatesAutomatically?: boolean; pythonPath?: string; condaRootPath?: string; } } let service: IService = { requirements: ['IRegistry'], provides: 'IApplication', activate: (registry: IRegistry): IApplication => { return new JupyterApplication(registry); } }; export default service;
the_stack
import util from '../common/util' /** Private enumaration to determine the value (new value or old value) should be applied during action */ enum HistoryValue { New, Old, } /** Private interface hack to access properties of objects via `any` */ type IIndexedObject = Record<string, any> /** Private class for historical actions */ class Action<V> { /** Field to store old value (=overwritten value) */ public readonly oldValue: V /** Field to store new value (=overwriting value) */ public readonly newValue: V /** Field to store description */ public readonly text: string /** Field to store apply function */ private readonly applyFn: (value: V) => void /** Field to store functions to emit after execution of action */ private readonly emits: ((value: V, oldValue: V) => void)[] = [] /** Reference to History */ private readonly history: History public applyImmediate = true public constructor( history: History, oldValue: V, newValue: V, text: string, applyFn: (value: V) => void ) { this.history = history this.oldValue = oldValue this.newValue = newValue this.text = text this.applyFn = applyFn } /** * Commit the action to the history * This allows for emits to be set up first */ public commit(): this { if (this.applyImmediate) { this.apply() } this.history.commitTransaction() return this } /** * Execute action and therfore apply value * @param value Whether to apply the new or the old value (Default: New) */ public apply(value: HistoryValue = HistoryValue.New): void { const newValue = value === HistoryValue.New ? this.newValue : this.oldValue const oldValue = value === HistoryValue.New ? this.oldValue : this.newValue this.applyFn(newValue) for (const f of this.emits) { f(newValue, oldValue) } } /** * Adds the function to a queue * * The function will be executed after the action has been applied */ public onDone(f: (newValue: V, oldValue: V) => void): Action<V> { this.emits.push(f) return this } } /** A wrapper that stores multiple `Action`s */ class Transaction { /** Field to store description */ public text: string /** Should actions be applied immediately */ private applyImmediate: boolean /** Field to store historical actions */ private readonly actions: Action<unknown>[] = [] public constructor(text?: string, applyImmediate?: boolean) { this.text = text this.applyImmediate = applyImmediate } public empty(): boolean { return this.actions.length === 0 } public apply(): void { if (this.applyImmediate) return for (const action of this.actions) { action.apply(HistoryValue.New) } } /** Undo all actions from this transaction in reversed order */ public undo(): void { const reversed = this.actions.map((_, i, arr) => arr[arr.length - 1 - i]) for (const action of reversed) { action.apply(HistoryValue.Old) } } /** Redo all actions from this transaction */ public redo(): void { for (const action of this.actions) { action.apply(HistoryValue.New) } } /** Logs all actions */ public log(): void { console.log(`[DO] ${this.text}:`) this.actions.forEach((a, i) => console.log('\t', i, a.text, ' - ', a.oldValue, ' -> ', a.newValue) ) } /** Add action to this transaction */ public push(action: Action<unknown>): void { if (this.text === undefined && this.actions.length === 0) { this.text = action.text } action.applyImmediate = this.applyImmediate this.actions.push(action) } } /** * **Component to store history for undo / redo actions** * * - Supports history for maps and for objects * - Supports changing values in nested arrays and objects * - Supports multiple actions being applied as a single action via transaction (only 1 undo / redo needed to revert) * - Supports nested transactions * - Supports emitting of functions to be executed subsequently to historical action on undo / redo * - Supports history length constraint * * @example * // Import and init * import History from './history' * const history = new History() * * // Update value of object * const o = { name: 'test name' } * history.updateValue(o, ['name'], 'updated name', 'Update Object Name').commit() * * // Update value of nested object * const o = { name: { nestedName: 'test name' } } * history.updateValue(o, ['name', 'nestedName'], 'updated name', 'Update Object Name').commit() * * // Update item of map * const m: Map<number, string> = new Map() * m.push(1, 'fff') * history.updateMap(m, 1, 'updated fff', 'Update Map Item') * * // Transaction of 2 actions and naming of transaction * const o = { firstName: 'test first name', lastName: 'test last name'} * history.startTransaction('Update 2 values') * history.updateValue(o, ['firstName'], 'update first name').commit() * history.updateValue(o, ['lastName'], 'update last name').commit() * history.commitTransaction() * * // Emit function after action execution * const o = { name: 'test name'} * history.updateValue(o, ['name'], 'updated name', 'Update Object Name').onDone(name => console.log(name)).commit() */ export class History { public logging = false private readonly MAX_HISTORY_LENGTH = 1000 private readonly MIN_HISTORY_LENGTH = 800 /** Counts how many times a 'startTransaction' was called so we know when 'commitTransaction' actually needs to apply */ private transactionCount = 0 private historyIndex = 0 private activeTransaction: Transaction private transactionHistory: Transaction[] = [] /** Removes all history entries */ public reset(): void { this.historyIndex = 0 this.transactionHistory = [] } /** Updates a value in an `Array` or `Object` at the specified path and stores it in the history */ public updateValue<T, V>(target: T, path: string[], value: V, text: string): Action<V> { const oldValue = this.GetValue<V>(target, path) const newValue = value const historyAction = new Action(this, oldValue, newValue, text, v => { if (v === undefined) { const current = this.GetValue(target, path) if (current !== undefined) { this.DeleteValue(target, path) } } else { this.SetValue<V>(target, path, v) } }) this.startTransaction() this.activeTransaction.push(historyAction) return historyAction } /** Updates a value in a `Map` and stores it in the history */ public updateMap<K, V>(target: Map<K, V>, key: K, value: V, text: string): Action<V> { const oldValue = target.get(key) const newValue = value const historyAction = new Action(this, oldValue, newValue, text, v => { if (v === undefined) { if (target.has(key)) { target.delete(key) } } else { target.set(key, v) } }) this.startTransaction() this.activeTransaction.push(historyAction) return historyAction } /** * Undo last action stored in history * @returns `false` if there are no actions left for undo * */ public undo(): boolean { if (this.historyIndex === 0) return false const historyEntry = this.transactionHistory[this.historyIndex - 1] historyEntry.undo() this.historyIndex -= 1 if (this.logging) { console.log(`[UNDO] ${historyEntry.text}`) } return true } /** * Redo last action stored in history * @returns `false` if there are no actions left for redo * */ public redo(): boolean { if (this.historyIndex === this.transactionHistory.length) return false const historyEntry = this.transactionHistory[this.historyIndex] historyEntry.redo() this.historyIndex += 1 if (this.logging) { console.log(`[REDO] ${historyEntry.text}`) } return true } /** * Starts a new transaction * @param text Description of transaction - If not specified it will be the description of the first action * @returns `false` if there is already an active transaction */ public startTransaction(text?: string, applyImmediate = true): boolean { this.transactionCount += 1 if (this.activeTransaction === undefined) { this.activeTransaction = new Transaction(text, applyImmediate) return true } else { return false } } /** * Commits the active transaction and pushes it into the history * @returns `false` if `transactionCount` is not 0 or transaction is empty */ public commitTransaction(): boolean { this.transactionCount -= 1 if (this.transactionCount === 0) { if (this.activeTransaction.empty()) return false while (this.transactionHistory.length > this.historyIndex) { this.transactionHistory.pop() } this.activeTransaction.apply() this.transactionHistory.push(this.activeTransaction) if (this.logging) { if (this.historyIndex !== 0 && this.historyIndex % 20 === 0) { console.clear() } this.activeTransaction.log() } this.activeTransaction = undefined if (this.historyIndex > this.MAX_HISTORY_LENGTH) { this.transactionHistory.splice(0, this.MAX_HISTORY_LENGTH - this.MIN_HISTORY_LENGTH) this.historyIndex = this.transactionHistory.length } this.historyIndex += 1 return true } return false } /** Gets the value of the `Array` or `Object` at the specified path */ private GetValue<V>(obj: IIndexedObject, path: string[]): V { if (path.length === 1) { if (util.objectHasOwnProperty(obj, path[0])) { return obj[path[0]] } else { return undefined } } else { return this.GetValue(obj[path[0]], path.slice(1)) } } /** Sets the value of the `Array` or `Object` at the specified path */ private SetValue<V>(obj: IIndexedObject, path: string[], value: V): void { if (path.length === 1) { if (Array.isArray(obj)) { obj.push(value) } else { obj[path[0]] = value } } else { this.SetValue<V>(obj[path[0]], path.slice(1), value) } } /** Deletes the value of the `Array` or `Object` at the specified path */ private DeleteValue(obj: IIndexedObject, path: string[]): void { if (path.length === 1) { if (Array.isArray(obj)) { obj.splice(Number(path[0]), 1) } else { delete obj[path[0]] } } else { this.DeleteValue(obj[path[0]], path.slice(1)) } } }
the_stack
* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. * In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator **/ gapi.load('client', () => { /** now we can use gapi.client */ gapi.client.load('androidenterprise', 'v1', () => { /** now we can use gapi.client.androidenterprise */ /** don't forget to authenticate your client before sending any request to resources: */ /** declare client_id registered in Google Developers Console */ const client_id = '<<PUT YOUR CLIENT ID HERE>>'; const scope = [ /** Manage corporate Android devices */ 'https://www.googleapis.com/auth/androidenterprise', ]; const immediate = true; gapi.auth.authorize({ client_id, scope, immediate }, authResult => { if (authResult && !authResult.error) { /** handle succesfull authorization */ run(); } else { /** handle authorization error */ } }); run(); }); async function run() { /** Retrieves the details of a device. */ await gapi.client.devices.get({ deviceId: "deviceId", enterpriseId: "enterpriseId", userId: "userId", }); /** * Retrieves whether a device's access to Google services is enabled or disabled. The device state takes effect only if enforcing EMM policies on Android * devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. This is * only supported for Google-managed users. */ await gapi.client.devices.getState({ deviceId: "deviceId", enterpriseId: "enterpriseId", userId: "userId", }); /** Retrieves the IDs of all of a user's devices. */ await gapi.client.devices.list({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Sets whether a device's access to Google services is enabled or disabled. The device state takes effect only if enforcing EMM policies on Android * devices is enabled in the Google Admin Console. Otherwise, the device state is ignored and all devices are allowed access to Google services. This is * only supported for Google-managed users. */ await gapi.client.devices.setState({ deviceId: "deviceId", enterpriseId: "enterpriseId", userId: "userId", }); /** Acknowledges notifications that were received from Enterprises.PullNotificationSet to prevent subsequent calls from returning the same notifications. */ await gapi.client.enterprises.acknowledgeNotificationSet({ notificationSetId: "notificationSetId", }); /** * Completes the signup flow, by specifying the Completion token and Enterprise token. This request must not be called multiple times for a given * Enterprise Token. */ await gapi.client.enterprises.completeSignup({ completionToken: "completionToken", enterpriseToken: "enterpriseToken", }); /** * Returns a unique token to access an embeddable UI. To generate a web UI, pass the generated token into the managed Google Play javascript API. Each * token may only be used to start one UI session. See the javascript API documentation for further information. */ await gapi.client.enterprises.createWebToken({ enterpriseId: "enterpriseId", }); /** * Deletes the binding between the EMM and enterprise. This is now deprecated. Use this method only to unenroll customers that were previously enrolled * with the insert call, then enroll them again with the enroll call. */ await gapi.client.enterprises.delete({ enterpriseId: "enterpriseId", }); /** Enrolls an enterprise with the calling EMM. */ await gapi.client.enterprises.enroll({ token: "token", }); /** Generates a sign-up URL. */ await gapi.client.enterprises.generateSignupUrl({ callbackUrl: "callbackUrl", }); /** Retrieves the name and domain of an enterprise. */ await gapi.client.enterprises.get({ enterpriseId: "enterpriseId", }); /** Returns the Android Device Policy config resource. */ await gapi.client.enterprises.getAndroidDevicePolicyConfig({ enterpriseId: "enterpriseId", }); /** * Returns a service account and credentials. The service account can be bound to the enterprise by calling setAccount. The service account is unique to * this enterprise and EMM, and will be deleted if the enterprise is unbound. The credentials contain private key data and are not stored server-side. * * This method can only be called after calling Enterprises.Enroll or Enterprises.CompleteSignup, and before Enterprises.SetAccount; at other times it * will return an error. * * Subsequent calls after the first will generate a new, unique set of credentials, and invalidate the previously generated credentials. * * Once the service account is bound to the enterprise, it can be managed using the serviceAccountKeys resource. */ await gapi.client.enterprises.getServiceAccount({ enterpriseId: "enterpriseId", keyType: "keyType", }); /** Returns the store layout for the enterprise. If the store layout has not been set, returns "basic" as the store layout type and no homepage. */ await gapi.client.enterprises.getStoreLayout({ enterpriseId: "enterpriseId", }); /** Establishes the binding between the EMM and an enterprise. This is now deprecated; use enroll instead. */ await gapi.client.enterprises.insert({ token: "token", }); /** * Looks up an enterprise by domain name. This is only supported for enterprises created via the Google-initiated creation flow. Lookup of the id is not * needed for enterprises created via the EMM-initiated flow since the EMM learns the enterprise ID in the callback specified in the * Enterprises.generateSignupUrl call. */ await gapi.client.enterprises.list({ domain: "domain", }); /** * Pulls and returns a notification set for the enterprises associated with the service account authenticated for the request. The notification set may be * empty if no notification are pending. * A notification set returned needs to be acknowledged within 20 seconds by calling Enterprises.AcknowledgeNotificationSet, unless the notification set * is empty. * Notifications that are not acknowledged within the 20 seconds will eventually be included again in the response to another PullNotificationSet request, * and those that are never acknowledged will ultimately be deleted according to the Google Cloud Platform Pub/Sub system policy. * Multiple requests might be performed concurrently to retrieve notifications, in which case the pending notifications (if any) will be split among each * caller, if any are pending. * If no notifications are present, an empty notification list is returned. Subsequent requests may return more notifications once they become available. */ await gapi.client.enterprises.pullNotificationSet({ requestMode: "requestMode", }); /** Sends a test notification to validate the EMM integration with the Google Cloud Pub/Sub service for this enterprise. */ await gapi.client.enterprises.sendTestPushNotification({ enterpriseId: "enterpriseId", }); /** Sets the account that will be used to authenticate to the API as the enterprise. */ await gapi.client.enterprises.setAccount({ enterpriseId: "enterpriseId", }); /** * Sets the Android Device Policy config resource. EMM may use this method to enable or disable Android Device Policy support for the specified * enterprise. To learn more about managing devices and apps with Android Device Policy, see the Android Management API. */ await gapi.client.enterprises.setAndroidDevicePolicyConfig({ enterpriseId: "enterpriseId", }); /** * Sets the store layout for the enterprise. By default, storeLayoutType is set to "basic" and the basic store layout is enabled. The basic layout only * contains apps approved by the admin, and that have been added to the available product set for a user (using the setAvailableProductSet call). Apps on * the page are sorted in order of their product ID value. If you create a custom store layout (by setting storeLayoutType = "custom" and setting a * homepage), the basic store layout is disabled. */ await gapi.client.enterprises.setStoreLayout({ enterpriseId: "enterpriseId", }); /** Unenrolls an enterprise from the calling EMM. */ await gapi.client.enterprises.unenroll({ enterpriseId: "enterpriseId", }); /** Removes an entitlement to an app for a user. */ await gapi.client.entitlements.delete({ enterpriseId: "enterpriseId", entitlementId: "entitlementId", userId: "userId", }); /** Retrieves details of an entitlement. */ await gapi.client.entitlements.get({ enterpriseId: "enterpriseId", entitlementId: "entitlementId", userId: "userId", }); /** Lists all entitlements for the specified user. Only the ID is set. */ await gapi.client.entitlements.list({ enterpriseId: "enterpriseId", userId: "userId", }); /** Adds or updates an entitlement to an app for a user. This method supports patch semantics. */ await gapi.client.entitlements.patch({ enterpriseId: "enterpriseId", entitlementId: "entitlementId", install: true, userId: "userId", }); /** Adds or updates an entitlement to an app for a user. */ await gapi.client.entitlements.update({ enterpriseId: "enterpriseId", entitlementId: "entitlementId", install: true, userId: "userId", }); /** Retrieves details of an enterprise's group license for a product. */ await gapi.client.grouplicenses.get({ enterpriseId: "enterpriseId", groupLicenseId: "groupLicenseId", }); /** Retrieves IDs of all products for which the enterprise has a group license. */ await gapi.client.grouplicenses.list({ enterpriseId: "enterpriseId", }); /** Retrieves the IDs of the users who have been granted entitlements under the license. */ await gapi.client.grouplicenseusers.list({ enterpriseId: "enterpriseId", groupLicenseId: "groupLicenseId", }); /** Requests to remove an app from a device. A call to get or list will still show the app as installed on the device until it is actually removed. */ await gapi.client.installs.delete({ deviceId: "deviceId", enterpriseId: "enterpriseId", installId: "installId", userId: "userId", }); /** Retrieves details of an installation of an app on a device. */ await gapi.client.installs.get({ deviceId: "deviceId", enterpriseId: "enterpriseId", installId: "installId", userId: "userId", }); /** Retrieves the details of all apps installed on the specified device. */ await gapi.client.installs.list({ deviceId: "deviceId", enterpriseId: "enterpriseId", userId: "userId", }); /** * Requests to install the latest version of an app to a device. If the app is already installed, then it is updated to the latest version if necessary. * This method supports patch semantics. */ await gapi.client.installs.patch({ deviceId: "deviceId", enterpriseId: "enterpriseId", installId: "installId", userId: "userId", }); /** Requests to install the latest version of an app to a device. If the app is already installed, then it is updated to the latest version if necessary. */ await gapi.client.installs.update({ deviceId: "deviceId", enterpriseId: "enterpriseId", installId: "installId", userId: "userId", }); /** Removes a per-device managed configuration for an app for the specified device. */ await gapi.client.managedconfigurationsfordevice.delete({ deviceId: "deviceId", enterpriseId: "enterpriseId", managedConfigurationForDeviceId: "managedConfigurationForDeviceId", userId: "userId", }); /** Retrieves details of a per-device managed configuration. */ await gapi.client.managedconfigurationsfordevice.get({ deviceId: "deviceId", enterpriseId: "enterpriseId", managedConfigurationForDeviceId: "managedConfigurationForDeviceId", userId: "userId", }); /** Lists all the per-device managed configurations for the specified device. Only the ID is set. */ await gapi.client.managedconfigurationsfordevice.list({ deviceId: "deviceId", enterpriseId: "enterpriseId", userId: "userId", }); /** Adds or updates a per-device managed configuration for an app for the specified device. This method supports patch semantics. */ await gapi.client.managedconfigurationsfordevice.patch({ deviceId: "deviceId", enterpriseId: "enterpriseId", managedConfigurationForDeviceId: "managedConfigurationForDeviceId", userId: "userId", }); /** Adds or updates a per-device managed configuration for an app for the specified device. */ await gapi.client.managedconfigurationsfordevice.update({ deviceId: "deviceId", enterpriseId: "enterpriseId", managedConfigurationForDeviceId: "managedConfigurationForDeviceId", userId: "userId", }); /** Removes a per-user managed configuration for an app for the specified user. */ await gapi.client.managedconfigurationsforuser.delete({ enterpriseId: "enterpriseId", managedConfigurationForUserId: "managedConfigurationForUserId", userId: "userId", }); /** Retrieves details of a per-user managed configuration for an app for the specified user. */ await gapi.client.managedconfigurationsforuser.get({ enterpriseId: "enterpriseId", managedConfigurationForUserId: "managedConfigurationForUserId", userId: "userId", }); /** Lists all the per-user managed configurations for the specified user. Only the ID is set. */ await gapi.client.managedconfigurationsforuser.list({ enterpriseId: "enterpriseId", userId: "userId", }); /** Adds or updates a per-user managed configuration for an app for the specified user. This method supports patch semantics. */ await gapi.client.managedconfigurationsforuser.patch({ enterpriseId: "enterpriseId", managedConfigurationForUserId: "managedConfigurationForUserId", userId: "userId", }); /** Adds or updates a per-user managed configuration for an app for the specified user. */ await gapi.client.managedconfigurationsforuser.update({ enterpriseId: "enterpriseId", managedConfigurationForUserId: "managedConfigurationForUserId", userId: "userId", }); /** Retrieves details of an Android app permission for display to an enterprise admin. */ await gapi.client.permissions.get({ language: "language", permissionId: "permissionId", }); /** * Approves the specified product and the relevant app permissions, if any. The maximum number of products that you can approve per enterprise customer is * 1,000. * * To learn how to use managed Google Play to design and create a store layout to display approved products to your users, see Store Layout Design. */ await gapi.client.products.approve({ enterpriseId: "enterpriseId", productId: "productId", }); /** * Generates a URL that can be rendered in an iframe to display the permissions (if any) of a product. An enterprise admin must view these permissions and * accept them on behalf of their organization in order to approve that product. * * Admins should accept the displayed permissions by interacting with a separate UI element in the EMM console, which in turn should trigger the use of * this URL as the approvalUrlInfo.approvalUrl property in a Products.approve call to approve the product. This URL can only be used to display * permissions for up to 1 day. */ await gapi.client.products.generateApprovalUrl({ enterpriseId: "enterpriseId", languageCode: "languageCode", productId: "productId", }); /** Retrieves details of a product for display to an enterprise admin. */ await gapi.client.products.get({ enterpriseId: "enterpriseId", language: "language", productId: "productId", }); /** * Retrieves the schema that defines the configurable properties for this product. All products have a schema, but this schema may be empty if no managed * configurations have been defined. This schema can be used to populate a UI that allows an admin to configure the product. To apply a managed * configuration based on the schema obtained using this API, see Managed Configurations through Play. */ await gapi.client.products.getAppRestrictionsSchema({ enterpriseId: "enterpriseId", language: "language", productId: "productId", }); /** Retrieves the Android app permissions required by this app. */ await gapi.client.products.getPermissions({ enterpriseId: "enterpriseId", productId: "productId", }); /** Finds approved products that match a query, or all approved products if there is no query. */ await gapi.client.products.list({ approved: true, enterpriseId: "enterpriseId", language: "language", maxResults: 4, query: "query", token: "token", }); /** Unapproves the specified product (and the relevant app permissions, if any) */ await gapi.client.products.unapprove({ enterpriseId: "enterpriseId", productId: "productId", }); /** * Removes and invalidates the specified credentials for the service account associated with this enterprise. The calling service account must have been * retrieved by calling Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling Enterprises.SetAccount. */ await gapi.client.serviceaccountkeys.delete({ enterpriseId: "enterpriseId", keyId: "keyId", }); /** * Generates new credentials for the service account associated with this enterprise. The calling service account must have been retrieved by calling * Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling Enterprises.SetAccount. * * Only the type of the key should be populated in the resource to be inserted. */ await gapi.client.serviceaccountkeys.insert({ enterpriseId: "enterpriseId", }); /** * Lists all active credentials for the service account associated with this enterprise. Only the ID and key type are returned. The calling service * account must have been retrieved by calling Enterprises.GetServiceAccount and must have been set as the enterprise service account by calling * Enterprises.SetAccount. */ await gapi.client.serviceaccountkeys.list({ enterpriseId: "enterpriseId", }); /** Deletes a cluster. */ await gapi.client.storelayoutclusters.delete({ clusterId: "clusterId", enterpriseId: "enterpriseId", pageId: "pageId", }); /** Retrieves details of a cluster. */ await gapi.client.storelayoutclusters.get({ clusterId: "clusterId", enterpriseId: "enterpriseId", pageId: "pageId", }); /** Inserts a new cluster in a page. */ await gapi.client.storelayoutclusters.insert({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Retrieves the details of all clusters on the specified page. */ await gapi.client.storelayoutclusters.list({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Updates a cluster. This method supports patch semantics. */ await gapi.client.storelayoutclusters.patch({ clusterId: "clusterId", enterpriseId: "enterpriseId", pageId: "pageId", }); /** Updates a cluster. */ await gapi.client.storelayoutclusters.update({ clusterId: "clusterId", enterpriseId: "enterpriseId", pageId: "pageId", }); /** Deletes a store page. */ await gapi.client.storelayoutpages.delete({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Retrieves details of a store page. */ await gapi.client.storelayoutpages.get({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Inserts a new store page. */ await gapi.client.storelayoutpages.insert({ enterpriseId: "enterpriseId", }); /** Retrieves the details of all pages in the store. */ await gapi.client.storelayoutpages.list({ enterpriseId: "enterpriseId", }); /** Updates the content of a store page. This method supports patch semantics. */ await gapi.client.storelayoutpages.patch({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Updates the content of a store page. */ await gapi.client.storelayoutpages.update({ enterpriseId: "enterpriseId", pageId: "pageId", }); /** Deleted an EMM-managed user. */ await gapi.client.users.delete({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Generates an authentication token which the device policy client can use to provision the given EMM-managed user account on a device. The generated * token is single-use and expires after a few minutes. * * This call only works with EMM-managed accounts. */ await gapi.client.users.generateAuthenticationToken({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Generates a token (activation code) to allow this user to configure their managed account in the Android Setup Wizard. Revokes any previously generated * token. * * This call only works with Google managed accounts. */ await gapi.client.users.generateToken({ enterpriseId: "enterpriseId", userId: "userId", }); /** Retrieves a user's details. */ await gapi.client.users.get({ enterpriseId: "enterpriseId", userId: "userId", }); /** Retrieves the set of products a user is entitled to access. */ await gapi.client.users.getAvailableProductSet({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Creates a new EMM-managed user. * * The Users resource passed in the body of the request should include an accountIdentifier and an accountType. * If a corresponding user already exists with the same account identifier, the user will be updated with the resource. In this case only the displayName * field can be changed. */ await gapi.client.users.insert({ enterpriseId: "enterpriseId", }); /** * Looks up a user by primary email address. This is only supported for Google-managed users. Lookup of the id is not needed for EMM-managed users because * the id is already returned in the result of the Users.insert call. */ await gapi.client.users.list({ email: "email", enterpriseId: "enterpriseId", }); /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the Users resource in the request body. Only the * displayName field can be changed. Other fields must either be unset or have the currently active value. This method supports patch semantics. */ await gapi.client.users.patch({ enterpriseId: "enterpriseId", userId: "userId", }); /** Revokes a previously generated token (activation code) for the user. */ await gapi.client.users.revokeToken({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Modifies the set of products that a user is entitled to access (referred to as whitelisted products). Only products that are approved or products that * were previously approved (products with revoked approval) can be whitelisted. */ await gapi.client.users.setAvailableProductSet({ enterpriseId: "enterpriseId", userId: "userId", }); /** * Updates the details of an EMM-managed user. * * Can be used with EMM-managed users only (not Google managed users). Pass the new details in the Users resource in the request body. Only the * displayName field can be changed. Other fields must either be unset or have the currently active value. */ await gapi.client.users.update({ enterpriseId: "enterpriseId", userId: "userId", }); } });
the_stack
import sinon from "sinon"; import Contract from "./Contract"; // In order to test the action package in a meaningful way, it needs // to be able to interact with contracts. import TasitContracts from "@tasit/contracts"; import ProviderFactory from "../ProviderFactory"; import { accounts, mineBlocks, createSnapshot, revertFromSnapshot, } from "@tasit/test-helpers"; const { local: localContracts } = TasitContracts; const { SampleContract } = localContracts; const { abi: sampleContractABI, address: SAMPLE_CONTRACT_ADDRESS, } = SampleContract; const provider = ProviderFactory.getProvider(); describe("TasitAction.Contract", () => { let sampleContract; let account; let action; let contractAbiString; // should connect to an existing contract beforeEach(async () => { await provider.ready; if (action) { expect(action.subscribedEventNames()).toHaveLength(0); } sampleContract = undefined; account = undefined; action = undefined; [account] = accounts; contractAbiString = sampleContractABI.toString(); sampleContract = new Contract(SAMPLE_CONTRACT_ADDRESS, contractAbiString); expect(sampleContract).toBeTruthy(); expect(sampleContract.getAddress()).toEqual(SAMPLE_CONTRACT_ADDRESS); expect(sampleContract.getValue).toBeTruthy(); expect(sampleContract.setValue).toBeTruthy(); expect(sampleContract._getProvider()).toBeTruthy(); expect(sampleContract.getABI()).toEqual(sampleContractABI); }); // revert blockchain snapshot afterEach(async () => { if (sampleContract) { sampleContract.unsubscribe(); expect(sampleContract.getEmitter()._events).toHaveLength(0); } if (action) { await action.waitForOneConfirmation(); action.unsubscribe(); expect(action.getEmitter()._events).toHaveLength(0); } }); describe("should throw error when instantiated with invalid args", () => { it("constructor without address and ABI", async () => { expect(() => { // @ts-ignore: TS2554 new Contract(); }).toThrow(); }); it("constructor without ABI", async () => { expect(() => { // @ts-ignore: TS2554 new Contract(SAMPLE_CONTRACT_ADDRESS); }).toThrow(); }); it("constructor without address but with ABI", async () => { expect(() => { // @ts-ignore: TS2345 new Contract(null, contractAbiString); }).toThrow(); }); it("constructor with invalid address and valid ABI", async () => { expect(() => { new Contract("invalid address", contractAbiString); }).toThrow(); }); it("constructor with valid address and invalid ABI", async () => { expect(() => { new Contract(SAMPLE_CONTRACT_ADDRESS, "invalid abi"); }).toThrow(); }); }); it("should call a read-only contract method", async () => { const value = await sampleContract.getValue(); expect(value).toBeTruthy(); }); describe("account setup tests", () => { it("should throw error when setting an account without argument", async () => { expect(() => { sampleContract.setAccount(); }).toThrow(); }); it("should throw error when setting invalid account", async () => { expect(() => { sampleContract.setAccount("invalid account"); }).toThrow(); }); it("should throw error when calling write method without account", async () => { expect(() => { sampleContract.setValue("hello world"); }).toThrow(); }); it("should throw error when calling write method after account removal", async () => { sampleContract.setAccount(account); sampleContract.removeAccount(); expect(() => { sampleContract.setValue("hello world"); }).toThrow(); }); }); describe("Contract errors behavior", () => { // assign an account to the contract beforeEach(() => { expect(() => { sampleContract.setAccount(account); }).not.toThrow(); }); describe("should trigger Contract error event", () => { it("on action error", async () => { const errorListener = sinon.fake(); sampleContract.on("error", errorListener); action = sampleContract.revertWrite("some string"); await action.send(); // Some error (orphan block, failed tx) events are being triggered only from the confirmationListener // See more: https://github.com/tasitlabs/tasit-sdk/issues/253 action.on("confirmation", () => { // do nothing }); await action.waitForOneConfirmation(); await mineBlocks(provider, 2); expect(errorListener.callCount).toBeGreaterThanOrEqual(1); }); it("and Action error event on action error", async () => { const contractErrorListener = sinon.fake(error => { const { message } = error; console.info(message); }); sampleContract.on("error", contractErrorListener); action = sampleContract.revertWrite("some string"); // Some error (orphan block, failed tx) events are being triggered only from the confirmationListener // See more: https://github.com/tasitlabs/tasit-sdk/issues/253 action.on("confirmation", () => { // do nothing }); const actionErrorListener = sinon.fake(error => { const { message } = error; console.info(message); action.off("error"); }); action.on("error", actionErrorListener); await action.send(); await action.waitForOneConfirmation(); await mineBlocks(provider, 1); expect(contractErrorListener.callCount).toEqual(1); expect(actionErrorListener.callCount).toEqual(1); }); it("on contract event listener error", done => { action = sampleContract.setValue("hello world"); const errorListener = sinon.fake(error => { const { message } = error; console.info(message); expect(eventListener.callCount).toBeGreaterThanOrEqual(1); done(); }); const eventListener = sinon.fake.throws(new Error()); sampleContract.on("error", errorListener); sampleContract.on("ValueChanged", eventListener); action.send(); }); }); it("throw error on revert read function", async () => { await expect(sampleContract.revertRead()).rejects.toThrow(); }); }); describe("Transactions (Actions) Subscription", () => { let rand; // assign an account to the contract beforeEach(() => { expect(() => { sampleContract.setAccount(account); }).not.toThrow(); rand = Math.floor(Math.random() * Math.floor(1000)).toString(); }); it("should throw when subscribing with invalid event name", async () => { action = sampleContract.setValue("hello world"); await action.send(); expect(() => { action.on("invalid", () => { // do nothing }); }).toThrow(); }); it("should throw when subscribing without listener", async () => { action = sampleContract.setValue("hello world"); await action.send(); expect(() => { action.on("confirmation"); }).toThrow(); }); it("should change contract state and trigger confirmation event one time", async () => { action = sampleContract.setValue(rand); await action.send(); // Waiting for 1st confirmation // For now ganache always mine a block after transaction creation // To avoid non-determinism it's recommended to wait that first confirmation if it could affect the test case result // See more: https://github.com/trufflesuite/ganache-core/issues/248#issuecomment-455354557 await action.waitForOneConfirmation(); const errorListener = sinon.fake(); const confirmationListener = sinon.fake(async () => { const value = await sampleContract.getValue(); expect(value).toEqual(rand); action.off("confirmation"); }); action.on("error", errorListener); action.once("confirmation", confirmationListener); await mineBlocks(provider, 2); expect(confirmationListener.callCount).toEqual(1); expect(errorListener.called).toBe(false); action.off("error"); expect(action.subscribedEventNames()).toHaveLength(0); }); it("should change contract state and trigger confirmation event", async () => { action = sampleContract.setValue(rand); await action.send(); await action.waitForOneConfirmation(); const confirmationListener = sinon.fake(async message => { const { data } = message; const { confirmations } = data; if (confirmations >= 7) { action.off("confirmation"); const value = await sampleContract.getValue(); expect(value).toEqual(rand); } }); const errorListener = sinon.fake(); action.on("error", errorListener); action.on("confirmation", confirmationListener); await mineBlocks(provider, 7); expect(confirmationListener.callCount).toEqual(6); expect(errorListener.called).toBe(false); }); it("should change contract state and trigger confirmation event - late subscription", async () => { action = sampleContract.setValue(rand); await action.send(); await action.waitForOneConfirmation(); await mineBlocks(provider, 5); const errorListener = sinon.fake(); const confirmationListener = sinon.fake(async message => { const { data } = message; const { confirmations } = data; if (confirmations >= 7) { action.off("confirmation"); const value = await sampleContract.getValue(); expect(value).toEqual(rand); } }); action.on("error", errorListener); action.on("confirmation", confirmationListener); await mineBlocks(provider, 2); // Non-deterministic expect(confirmationListener.callCount).toBeGreaterThanOrEqual(1); expect(errorListener.called).toBe(false); }); it("action should call error listener after timeout", done => { action = sampleContract.setValue("hello world"); action.setTimeout(100); const errorListener = sinon.fake(error => { const { eventName, message } = error; expect(eventName).toEqual("confirmation"); expect(message).toEqual("Event confirmation reached timeout."); expect(action.subscribedEventNames()).toEqual([ "error", "confirmation", ]); action.off("error"); action.off("confirmation"); done(); }); const confirmationListener = sinon.fake(() => { // do nothing }); action.on("confirmation", confirmationListener); action.on("error", errorListener); // Note: Sending this triggers a block being mined, // and since no additional blocks will be mined, // the timeout will be reached before another confirmation occurs action.send(); }); it("subscription should have one listener per event", async () => { action = sampleContract.setValue("hello world"); await action.send(); const listener1 = () => { // do nothing }; const listener2 = () => { // do nothing }; expect(action.subscribedEventNames()).toEqual(["error"]); action.on("confirmation", listener1); expect(() => { action.on("confirmation", listener2); }).toThrow(); expect(action.subscribedEventNames()).toEqual(["error", "confirmation"]); }); it("should remove an event", async () => { action = sampleContract.setValue("hello world"); await action.send(); const listener1 = () => { // do nothing }; expect(action.subscribedEventNames()).toEqual(["error"]); action.on("confirmation", listener1); expect(action.subscribedEventNames()).toEqual(["error", "confirmation"]); action.off("confirmation"); expect(action.subscribedEventNames()).toEqual(["error"]); }); // Note: Block reorganization is the situation where a client discovers a // new difficultywise-longest well-formed blockchain which excludes one or more blocks that // the client previously thought were part of the difficultywise-longest well-formed blockchain. // These excluded blocks become orphans. it("should emit error event when block reorganization occurs - block excluded", async () => { const confirmationFn = sinon.fake(); const errorFn = sinon.fake(); const confirmationListener = () => { confirmationFn(); }; const errorListener = error => { const { message } = error; // Note: This assertion will not fail the test case (UnhandledPromiseRejectionWarning) expect(message).toEqual( "Your action's position in the chain has changed in a surprising way." ); // But asserting fake function, if that throws, test case will fail. errorFn(); }; const snapshotId = await createSnapshot(provider); action = sampleContract.setValue("hello world"); await action.send(); action.on("confirmation", confirmationListener); action.on("error", errorListener); await mineBlocks(provider, 2); // Non-deterministic expect(confirmationFn.callCount).toBeGreaterThanOrEqual(1); await revertFromSnapshot(provider, snapshotId); await mineBlocks(provider, 2); // Note: Transaction no longer exists // If it isn't unset, afterEach hook will execute waitForOneConfirmation forever action.off("confirmation"); action = undefined; // Non-deterministic expect(errorFn.callCount).toBeGreaterThanOrEqual(1); }); // Note: Block reorganization is the situation where a client discovers a // new difficultywise-longest well-formed blockchain which excludes one or more blocks that // the client previously thought were part of the difficultywise-longest well-formed blockchain. // These excluded blocks become orphans. it("should emit error event when block reorganization occurs - tx confirmed twice", async () => { const confirmationListener = sinon.fake(); const errorFn = sinon.fake(); const errorListener = error => { const { message } = error; // Note: This assertion will not fail the test case (UnhandledPromiseRejectionWarning) expect(message).toEqual( "Your action's position in the chain has changed in a surprising way." ); // But asserting fake function, if that throws, test case will fail. errorFn(); }; action = sampleContract.setValue("hello world"); await action.send(); await action.waitForOneConfirmation(); action.on("error", errorListener); action.on("confirmation", confirmationListener); await mineBlocks(provider, 1); const snapshotId = await createSnapshot(provider); await mineBlocks(provider, 2); // Non-deterministic expect(confirmationListener.callCount).toBeGreaterThanOrEqual(1); await revertFromSnapshot(provider, snapshotId); // Note: Without that, ethers.provider will keep the same // receipt.confirmations as before snapshot reversion // See more: https://github.com/ethers-io/ethers.js/issues/385#issuecomment-455187735 action._refreshProvider(); await mineBlocks(provider, 2); // not always on the first new block because of pollingInterval vs blockTime issue // but the first poll after that 15 new blocks is emitting error event // Non-deterministic expect(errorFn.callCount).toBeGreaterThanOrEqual(1); }); it("should get action id (transactionHash)", async () => { action = sampleContract.setValue(rand); await action.send(); const actionId = await action.getId(); expect(typeof actionId).toBe("string"); expect(actionId).toHaveLength(66); }); it("should be able to listen to an event before sending", async () => { const confirmationListener = sinon.fake(async () => { action.off("confirmation"); }); const errorListener = sinon.fake(); action = sampleContract.setValue(rand); action.on("error", errorListener); action.on("confirmation", confirmationListener); await mineBlocks(provider, 2); await action.send(); await action.waitForOneConfirmation(); await mineBlocks(provider, 2); // Non-determinitic expect(confirmationListener.callCount).toBeGreaterThanOrEqual(1); expect(errorListener.called).toBe(false); }); it("'once' listener should be unsubscribed only after user listener function was called", async () => { action = sampleContract.setValue(rand); const errorListener = sinon.fake(error => { const { message } = error; console.info(message); action.off("error"); }); const confirmationListener = sinon.fake(); action.on("error", errorListener); action.once("confirmation", confirmationListener); // Forcing internal (block) listener to be called before the transaction is sent await mineBlocks(provider, 2); await action.send(); await action.waitForOneConfirmation(); await mineBlocks(provider, 2); expect(confirmationListener.called).toBe(true); expect(errorListener.called).toBe(false); }); }); describe("Contract Events Subscription", () => { // assign an account to the contract beforeEach(() => { expect(() => { sampleContract.setAccount(account); }).not.toThrow(); }); it("should trigger an event one time when you're listening to that event and the contract triggers it", done => { action = sampleContract.setValue("hello world"); const valueChangedListener = sinon.fake(() => { sampleContract.off("error"); expect(sampleContract.subscribedEventNames()).toHaveLength(0); done(); }); const errorListener = sinon.fake(error => { done(error); }); sampleContract.on("error", errorListener); sampleContract.once("ValueChanged", valueChangedListener); action.send(); }); it("should be able to listen to an event triggered by the contract", done => { action = sampleContract.setValue("hello world"); const errorListener = sinon.fake(error => { done(error); }); const valueChangedListener = sinon.fake(() => { sampleContract.off("ValueChanged"); sampleContract.off("error"); done(); }); sampleContract.on("error", errorListener); sampleContract.on("ValueChanged", valueChangedListener); action.send(); }); // Non-deterministic test it.skip("contract should call error listener after timeout", done => { sampleContract.setTimeout(100); action = sampleContract.setValue("hello world"); const errorListener = sinon.fake(error => { const { eventName, message } = error; expect(eventName).toEqual("ValueChanged"); expect(message).toEqual("Event ValueChanged reached timeout."); expect(sampleContract.subscribedEventNames()).toEqual([ "ValueChanged", "error", ]); sampleContract.off("error"); sampleContract.off("ValueChanged"); done(); }); const confirmationListener = sinon.fake(() => { // do nothing }); sampleContract.on("ValueChanged", confirmationListener); sampleContract.on("error", errorListener); // Note: Sending this triggers a block being mined, // and since no additional blocks will be mined, // the timeout will be reached before another confirmation occurs action.send(); }); it("should throw error when listening on invalid event", async () => { expect(() => { sampleContract.on("InvalidEvent", () => { // do nothing }); }).toThrow(); }); it("subscription should have one listener per event", async () => { const listener1 = () => { // do nothing }; const listener2 = () => { // do nothing }; expect(sampleContract.subscribedEventNames()).toHaveLength(0); sampleContract.on("ValueChanged", listener1); expect(() => { sampleContract.on("ValueChanged", listener2); }).toThrow(); expect(sampleContract.subscribedEventNames()).toEqual(["ValueChanged"]); }); it("should remove an event", async () => { const listener1 = () => { // do nothing }; expect(sampleContract.subscribedEventNames()).toHaveLength(0); sampleContract.on("ValueChanged", listener1); expect(sampleContract.subscribedEventNames()).toEqual(["ValueChanged"]); sampleContract.off("ValueChanged"); expect(sampleContract.subscribedEventNames()).toHaveLength(0); }); it("should manage many listeners", async () => { const listener1 = () => { // do nothing }; const listener2 = () => { // do nothing }; const listener3 = () => { // do nothing }; expect(sampleContract.subscribedEventNames()).toHaveLength(0); sampleContract.on("ValueChanged", listener1); sampleContract.on("ValueRemoved", listener2); expect(sampleContract.subscribedEventNames()).toEqual([ "ValueChanged", "ValueRemoved", ]); sampleContract.off("ValueRemoved"); expect(sampleContract.subscribedEventNames()).toEqual(["ValueChanged"]); sampleContract.on("ValueRemoved", listener3); expect(sampleContract.subscribedEventNames()).toEqual([ "ValueChanged", "ValueRemoved", ]); sampleContract.unsubscribe(); expect(sampleContract.subscribedEventNames()).toHaveLength(0); }); }); // Send method interface: Contract.send(tx: msg, bool: free) => Subscription // On free send how know if contract-based-account should be used? it.skip("should send a signed message", async () => { // do nothing }); });
the_stack
import Observable = require("data/observable"); import TypeUtils = require("utils/types"); /** * Name of the property for a "real" / non-routed value. */ export const INNER_VALUE_PROPERTY = 'innerValue'; /** * Name of the property for a routed value. */ export const VALUE_PROPERTY = 'value'; /** * List of router stradegies. */ export enum RouterStradegy { /** * Take the value from parent (if greater) */ Ascending, /** * Take the value from parent (if smaller) */ Descending, } /** * List of values that represent the state of a traffic light. */ export enum TraficLightState { /** * None (gray) **/ None = 0, /** * OK (green) **/ OK = 1, /** * Warning (yellow) **/ Warning = 2, /** * Error (red) **/ Error = 3, /** * Fatal error (yellow / red) **/ FatalError = 4, } /** * A routed value. */ export class RoutedValue<T> extends Observable.Observable { /** * Stores the children. */ protected _children: RoutedValue<T>[] = []; /** * Stores the comparer for the values. */ protected _comparer: (x: T, y: T) => number; /** * Stores the "real" inner value of that instance. */ protected _innerValue: T; private _name: string; /** * Stores the parents. */ protected _parents: RoutedValue<T>[] = []; /** * Stores the stradegy. */ protected _stradegy: RouterStradegy; private _tag: any; /** * Initializes a new instance of that class. * * @param {RouterStradegy} [stradegy] The router stradegy. * @param {Function} [comparer] The comparer for the values. */ constructor(stradegy: RouterStradegy = RouterStradegy.Ascending, comparer?: (x: T, y: T) => number) { super(); this._stradegy = stradegy; this._comparer = comparer; if (TypeUtils.isNullOrUndefined(this._comparer)) { this._comparer = (x, y): number => { if (x < y) { return -1; } if (x > y) { return 1; } return 0; }; } } /** * Adds a list of children. * * @chainable * * @param {RoutedState} ...children One or more child to add. */ public addChildren(...children: RoutedValue<T>[]): RoutedValue<T> { return this.addChildArray(children); } /** * Adds a list of children. * * @chainable * * @param {Array} children The children to add. * * @throws A child object is already a parent. */ public addChildArray(children: RoutedValue<T>[]): RoutedValue<T> { if (TypeUtils.isNullOrUndefined(children)) { return this; } for (var i = 0; i < children.length; i++) { var c = children[i]; if (TypeUtils.isNullOrUndefined(c)) { continue; } for (var ii = 0; ii < this._parents.length; ii++) { var p = this._children[ii]; if (<any>p === <any>c) { throw "Child object is already a parent!"; } } this._children.push(c); c.addParentItem(this, false); } return this; } /** * Adds a parent item. * * @param {RoutedValue} parent The parent item to add. * @param {Boolean} addChild Also add that instance as child item for 'parent' or not. * * @throws Parent object is already a child. */ protected addParentItem(parent: RoutedValue<T>, addChild: boolean) { var me = this; for (var i = 0; i < me._children.length; i++) { var c = me._children[i]; if (<any>c === parent) { throw "Parent object is already a child!"; } } if (addChild) { parent.addChildren(me); } parent.on(Observable.Observable.propertyChangeEvent, (e: Observable.PropertyChangeData) => { var sender = <RoutedValue<T>>e.object; switch (e.propertyName) { case VALUE_PROPERTY: if (me.shouldTakeParentValue(sender.value)) { me.raiseValueChanged(); } break; } }); var oldValue = me.value; me._parents.push(parent); if (me.shouldTakeParentValue(parent.value, oldValue)) { me.raiseValueChanged(); } } /** * Adds a list of parents. * * @chainable * * @param {RoutedState} ...parents One or more parent to add. */ public addParents(...parents: RoutedValue<T>[]): RoutedValue<T> { return this.addParentArray(parents); } /** * Adds a list of parents. * * @chainable * * @param {Array} parents The parents to add. */ public addParentArray(parents: RoutedValue<T>[]): RoutedValue<T> { if (TypeUtils.isNullOrUndefined(parents)) { return this; } for (var i = 0; i < parents.length; i++) { var p = parents[i]; if (TypeUtils.isNullOrUndefined(p)) { continue; } this.addParentItem(p, true); } return this; } /** * Gets or sets the "real" (not routed) value of that instance. */ public get innerValue(): T { return this._innerValue; } public set innerValue(newValue: T) { var oldInnerValue = this._innerValue; var oldValue = this.value; this._innerValue = newValue; if (oldInnerValue !== newValue) { this.notifyPropertyChange(INNER_VALUE_PROPERTY, newValue); } if (oldValue !== this.value) { this.raiseValueChanged(); } } /** * Gets or sets the name of that instance. */ public get name(): string { return this._name; } public set name(newValue: string) { var oldValue = this._name; this._name = newValue; if (newValue !== oldValue) { this.notifyPropertyChange('name', newValue); } } /** * Hooks a changed event listener for 'value' property. * * @param {Function} listener The listener to register. * * @return {Function} The underlying 'hook' function that has been used for 'on' method. */ public onValueChanged(listener: (newValue: T, object: RoutedValue<T>) => void): (e: Observable.PropertyChangeData) => void { if (TypeUtils.isNullOrUndefined(listener)) { return; } var propertyChange = (e: Observable.PropertyChangeData) => { switch (e.propertyName) { case VALUE_PROPERTY: listener(e.value, <RoutedValue<T>>e.object); break; } }; this.on(Observable.Observable.propertyChangeEvent, propertyChange); return propertyChange; } /** * Raises the property change event for the value property. */ public raiseValueChanged() { var thisValue = this.value; this.notifyPropertyChange(VALUE_PROPERTY, thisValue); for (var i = 0; i < this._children.length; i++) { var c = this._children[i]; c.raiseValueChanged(); } } /** * Checks if a parent value should be taken instead of the own one. * This depends on the value comparer function that is used by that instance. * * @param {T} parentValue The "parent" value. * @param {T} [thisValue] The custom value to take that is handled as "own" value. * * @return {Boolean} 'parentValue' should be taken or now. */ public shouldTakeParentValue(parentValue: T, thisValue?: T): boolean { if (arguments.length < 2) { thisValue = this._innerValue; } var compVal = this._comparer(thisValue, parentValue); switch (this.stradegy) { case RouterStradegy.Ascending: return compVal < 0; // parent is greater case RouterStradegy.Descending: return compVal > 0; // "own" value is greater } } /** * Gets the router stradegy. */ public get stradegy(): RouterStradegy { return this._stradegy; } /** * Gets or sets an object / value that should be linked with that instance. */ public get tag(): any { return this._tag; } public set tag(newValue: any) { var oldValue = this._tag; this._tag = newValue; if (newValue !== oldValue) { this.notifyPropertyChange('tag', newValue); } } /** * Gets the routed value. */ public get value(): T { var result: T = this._innerValue; // check parents for (var i = 0; i < this._parents.length; i++) { var p = this._parents[i]; var pVal = p.value; if (this.shouldTakeParentValue(pVal, result)) { result = pVal; } } return result; } } /** * A routed number. */ export class RoutedNumber extends RoutedValue<number> { constructor() { super(); this._innerValue = 0; } } /** * A routed traffic light. */ export class TrafficLight extends RoutedValue<TraficLightState> { }
the_stack
import { RenameProvider, ProviderResult, WorkspaceEdit, TextDocument, Position, CancellationToken } from 'vscode'; import * as vscode from 'vscode' import { LParse } from '../parser/LParse' import { LFileMgr } from './LFileMgr' import { LCItem } from "../provider/LCItem" import { LFile } from "./LFile" import { LFItem } from "./LFItem" import { LFrag, LToken, LTT, LComment, LRange, LET, LError, LFT } from '../parser/LEntity' import { LGItem } from "../provider/LGItem" import { Helper } from '../context/Helper' import { Uri } from "vscode" import { ExtMgr } from '../context/ExtMgr' export class PvdDefinition implements vscode.DefinitionProvider { public provideDefinition( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.Location> { return new Promise<vscode.Location>((resolve, reject) => { return resolve(this.parse(document, position)); }); } private parse(document: vscode.TextDocument, position: vscode.Position): vscode.Location { var lineText = document.lineAt(position.line).text; if (lineText.trim().substring(0, 4) == "---@") { // 注解 return this.findComment(lineText, position) } var tempStr = lineText.substring(position.character) var endIndex = tempStr.indexOf('"') if (endIndex > -1) { var startStr = lineText.substring(0, position.character) var findex = startStr.lastIndexOf('"') if (findex > -1) { var moduleName = lineText.substring(findex + 1, endIndex + position.character) if (moduleName.length > 0) { var uri = LFItem.instance().getUriCompletionByModuleName(moduleName) if (uri) { // 路径 var loc: vscode.Location = new vscode.Location(uri, new vscode.Position(0, 0)) return loc } } } } let offset = document.offsetAt(position); let text = document.getText(); let byteOffset = 0; var isFun: boolean = false; var nameChats: Array<string> = new Array<string>(); var luaManager: LFileMgr = LParse.ins.fileMgr; var lp: LParse = LParse.ins; var tokens: Array<LToken> = Helper.GetTokens(document, position) var isFun: boolean = false var i: number = 0; var lashToken: LToken = null if (tokens) { i = tokens.length - 1; } try { while (i >= 0) { var token: LToken = tokens[i]; i--; if (lp.Compare('function', token, LTT.Keyword)) { return null; } if (token.type == LTT.Keyword || lp.Compare('(', token, LTT.Punctuator) || lp.Compare(')', token, LTT.Punctuator) ) { isFun = true break; } else if ( lp.Compare('+', token, LTT.Punctuator) || lp.Compare('-', token, LTT.Punctuator) || lp.Compare('*', token, LTT.Punctuator) || lp.Compare('/', token, LTT.Punctuator) || lp.Compare('>', token, LTT.Punctuator) || lp.Compare('<', token, LTT.Punctuator) || lp.Compare('>=', token, LTT.Punctuator) || lp.Compare('<=', token, LTT.Punctuator) || lp.Compare('==', token, LTT.Punctuator) || lp.Compare('~=', token, LTT.Punctuator) || lp.Compare('=', token, LTT.Punctuator) || lp.Compare('#', token, LTT.Punctuator) || lp.Compare('}', token, LTT.Punctuator) || lp.Compare('{', token, LTT.Punctuator) || lp.Compare(']', token, LTT.Punctuator) || lp.Compare('[', token, LTT.Punctuator) || lp.Compare(',', token, LTT.Punctuator) || lp.Compare(';', token, LTT.Punctuator) || lp.Compare('else', token, LTT.Punctuator) || lp.Compare('elseif', token, LTT.Punctuator) || lp.Compare('do', token, LTT.Keyword) ) { break; } nameChats.push(token.value); lashToken = token; if (i >= 0) { var nextToken: LToken = tokens[i]; if (token.type == LTT.Identifier && ( nextToken.type == LTT.Identifier || nextToken.type == LTT.NumericLiteral || nextToken.type == LTT.Keyword || nextToken.type == LTT.StringLiteral || nextToken.type == LTT.NilLiteral || nextToken.type == LTT.BooleanLiteral)) { break; } } } } catch (err) { Helper.Log(err) } nameChats = nameChats.reverse() for (let i = offset; i < text.length; i++) { var chat = text.charCodeAt(i) if (Helper.IsIdentifierPart(chat)) { nameChats.push(text[i]) } else if (text[i] == '=' || text[i] == '==' || text[i] == '~=' || text[i] == ')' || text[i] == ']' || text[i] == '[' || text[i] == '}' || text[i] == '+' || text[i] == '-' || text[i] == '*' || text[i] == '/' || text[i] == '>' || text[i] == '<' || text[i] == '>=' || text[i] == '<=' ) { break; } else { isFun = chat == 40; break; } } var n = "" nameChats.forEach(c => { n += c; }); var keyNames: Array<string> = new Array<string>(); var tempNames: Array<string> = n.split('.') for (var i = 0; i < tempNames.length; i++) { if (i == tempNames.length - 1) { var tempNames1 = tempNames[tempNames.length - 1].split(':') for (var j = 0; j < tempNames1.length; j++) { keyNames.push(tempNames1[j]) } } else { keyNames.push(tempNames[i]) } } var isSelf: boolean = false; if (keyNames[0] == 'self') { var data = Helper.GetSelfToModuleName(tokens, lp) keyNames[0] = data.moduleName isSelf = true } var loc = this.find(document, keyNames, tokens, isSelf, isFun) return loc } private find(document: vscode.TextDocument, keyNames: Array<string>, tokens: Array<LToken>, isSelf: boolean, isFun: boolean): vscode.Location { var loc var fileMgr = LParse.ins.fileMgr var functionNames: Array<string> = Helper.GetCurrentFunctionName(tokens) var isLocal = false var file = fileMgr.getFile(document.uri) var rootVar = keyNames[0] var lastVar = keyNames[keyNames.length - 1] var root: LCItem var dFile: LFile var isSingle = keyNames.length == 1 // is local var in file try { file.locals.items.forEach((temp) => { if (temp.label == rootVar) { if (temp.refField) { temp.refField.forEach(keys => { if (keys && keys.length > 0) { rootVar = keys[0] if (isSingle) { root = temp } throw null } }); } } }) } catch { } if (root) { loc = new vscode.Location(root.uri, root.position) } else { if (functionNames != null && functionNames.length > 0) { var rootFuncName = functionNames[0] var rootFunc = file.funcFields.get(rootFuncName) if (rootFunc == null) { rootFunc = file.funcFields.get(Helper.GetFunctionName(tokens, 0)) } var symbol = file.getSymbol(rootFuncName) if (symbol == null) { symbol = file.getSymbol(Helper.GetFunctionName(tokens, 0)) } if (rootFunc) { if (isSingle) { if (symbol) { try { symbol.args.forEach((arg) => { if (arg.label == rootVar) { root = arg root.uri = document.uri throw null } }) } catch { } } if (root == null) { root = rootFunc.getItemByKey(rootVar) } } else { if (symbol) { var checkAssign = function () { var tempName for (var j = 0; j < file.tokens.length; j++) { var token = file.tokens[j] var useful = false if (token.line >= symbol.range.start.line) { useful = true } if (useful && token.value == rootVar) { if (token.next && token.next.value == "=" && token.next.next && token.next.next.type == LTT.Identifier) { var tempRoot = rootFunc.getItemByKey(rootVar) if (tempRoot && tempRoot.refClazz) { rootVar = tempRoot.refClazz tempName = null break } // else if (tempRoot && tempRoot.refField) { // try { // tempRoot.refField.forEach(keys => { // if (keys && keys.length > 0) { // tempName = keys[0] // throw null // } // }); // } catch{ } // } else if (tempRoot && tempRoot.refFunc) { // try { // tempRoot.refFunc.forEach(keys => { // if (keys && keys.length > 0) { // rootVar = keys[0] // throw null // } // }); // } catch{ } // tempName = null // break // } else { tempName = token.next.next.value } } } if (token.line > symbol.range.end.line) { break } } if (tempName) { rootVar = tempName tempName = null checkAssign() } } checkAssign() } } } } } if (root) { loc = new vscode.Location(root.uri, root.position) } else { dFile = fileMgr.getFileByDefine(rootVar) if (dFile) { if (isSingle) { root = dFile.fields.getItemByKey(rootVar) if (root == null) { root = dFile.funcs.getItemByKey(rootVar) } } else { root = dFile.funcs.getItemByKey(rootVar) if (root) { for (var i = 1; i < keyNames.length; i++) { var key = keyNames[i] if (root == null) { break } root = root.getItemByKey(key) } } if (root == null) { root = dFile.fields.getItemByKey(rootVar) if (root) { for (var i = 1; i < keyNames.length; i++) { var key = keyNames[i] if (root == null) { break } root = root.getItemByKey(key) } } } } if (root) { loc = new vscode.Location(root.uri, root.position) } } } return loc } private findToken(tokens: Array<LToken>, tokenIdx: number, keys: Array<string>, keyIdx: number): LToken { var token = tokens[tokenIdx] var nextToken = tokens[tokenIdx + 1] if (token == null) return null if (token.value == keys[keyIdx]) { if (keyIdx == keys.length - 1) { return token } else if (nextToken) { if (nextToken.value == "." || nextToken.value == ":") { return this.findToken(tokens, tokenIdx + 2, keys, keyIdx + 1); } else { return null } } } else { return null } } private findItem(rootItem: LCItem, keys: Array<string>, index: number) { if (rootItem == null) return null rootItem = rootItem.getItemByKey(keys[index]) if (index == keys.length - 1) { return rootItem } else { if (rootItem != null) { index++; rootItem = this.findItem(rootItem, keys, index) return rootItem } else { return null } } } private findComment(line: string, position: vscode.Position): vscode.Location { var str = line.trim() var strs = str.split("---@") if (strs.length > 1) { strs = strs[1].split(" ") if (strs.length > 1) { var names = [] for (var i = 1; i < strs.length; i++) { var temp = strs[i] if (temp != ":" && temp != "") { names.push(temp) } } if (names.length > 0) { var moduleName = names[0] if (moduleName) { var fileMgr = LParse.ins.fileMgr var dfile = fileMgr.getFileByDefine(moduleName) if (dfile) { var item = dfile.fields.getItemByKey(moduleName) if (item) { return new vscode.Location(item.uri, item.position) } } } } } } return null } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { LoadTests } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { LoadTestClient } from "../loadTestClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { LoadTestResource, LoadTestsListBySubscriptionNextOptionalParams, LoadTestsListBySubscriptionOptionalParams, LoadTestsListByResourceGroupNextOptionalParams, LoadTestsListByResourceGroupOptionalParams, LoadTestsListBySubscriptionResponse, LoadTestsListByResourceGroupResponse, LoadTestsGetOptionalParams, LoadTestsGetResponse, LoadTestsCreateOrUpdateOptionalParams, LoadTestsCreateOrUpdateResponse, LoadTestResourcePatchRequestBody, LoadTestsUpdateOptionalParams, LoadTestsUpdateResponse, LoadTestsDeleteOptionalParams, LoadTestsListBySubscriptionNextResponse, LoadTestsListByResourceGroupNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing LoadTests operations. */ export class LoadTestsImpl implements LoadTests { private readonly client: LoadTestClient; /** * Initialize a new instance of the class LoadTests class. * @param client Reference to the service client */ constructor(client: LoadTestClient) { this.client = client; } /** * Lists loadtests resources in a subscription. * @param options The options parameters. */ public listBySubscription( options?: LoadTestsListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<LoadTestResource> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: LoadTestsListBySubscriptionOptionalParams ): AsyncIterableIterator<LoadTestResource[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: LoadTestsListBySubscriptionOptionalParams ): AsyncIterableIterator<LoadTestResource> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Lists loadtest resources in a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: LoadTestsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<LoadTestResource> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: LoadTestsListByResourceGroupOptionalParams ): AsyncIterableIterator<LoadTestResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: LoadTestsListByResourceGroupOptionalParams ): AsyncIterableIterator<LoadTestResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists loadtests resources in a subscription. * @param options The options parameters. */ private _listBySubscription( options?: LoadTestsListBySubscriptionOptionalParams ): Promise<LoadTestsListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * Lists loadtest resources in a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: LoadTestsListByResourceGroupOptionalParams ): Promise<LoadTestsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Get a LoadTest resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param loadTestName Load Test name. * @param options The options parameters. */ get( resourceGroupName: string, loadTestName: string, options?: LoadTestsGetOptionalParams ): Promise<LoadTestsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadTestName, options }, getOperationSpec ); } /** * Create or update LoadTest resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param loadTestName Load Test name. * @param loadTestResource LoadTest resource data * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, loadTestName: string, loadTestResource: LoadTestResource, options?: LoadTestsCreateOrUpdateOptionalParams ): Promise<LoadTestsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadTestName, loadTestResource, options }, createOrUpdateOperationSpec ); } /** * Update a loadtest resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param loadTestName Load Test name. * @param loadTestResourcePatchRequestBody LoadTest resource update data * @param options The options parameters. */ update( resourceGroupName: string, loadTestName: string, loadTestResourcePatchRequestBody: LoadTestResourcePatchRequestBody, options?: LoadTestsUpdateOptionalParams ): Promise<LoadTestsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadTestName, loadTestResourcePatchRequestBody, options }, updateOperationSpec ); } /** * Delete a LoadTest resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param loadTestName Load Test name. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, loadTestName: string, options?: LoadTestsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, loadTestName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Delete a LoadTest resource. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param loadTestName Load Test name. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, loadTestName: string, options?: LoadTestsDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, loadTestName, options ); return poller.pollUntilDone(); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: LoadTestsListBySubscriptionNextOptionalParams ): Promise<LoadTestsListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: LoadTestsListByResourceGroupNextOptionalParams ): Promise<LoadTestsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.LoadTestService/loadTests", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadTestResourcePageList }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadTestResourcePageList }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadTestResource }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.loadTestName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.LoadTestResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.loadTestResource, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.loadTestName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.LoadTestResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.loadTestResourcePatchRequestBody, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.loadTestName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.loadTestName ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadTestResourcePageList }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadTestResourcePageList }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer };
the_stack
import * as ts from 'typescript'; import * as base from './base'; import {FacadeConverter, identifierCanBeRenamed, isValidIdentifier} from './facade_converter'; import {Transpiler} from './main'; import {MergedMember, MergedParameter, MergedType, MergedTypeParameters} from './merge'; const PRIVATE_CLASS_INSTANCE_IN_EXTENSIONS = 'tt'; const enum emitPropertyMode { getter, setter } type emitPropertyOptions = { mode: emitPropertyMode, declaration: ts.PropertyDeclaration|ts.PropertySignature|ts.VariableDeclaration| ts.ParameterDeclaration, emitJsAnnotation: boolean, isExternal: boolean, emitBody?: (declaration: ts.PropertyDeclaration|ts.PropertySignature) => void }; export function isFunctionLikeProperty( decl: ts.VariableDeclaration|ts.ParameterDeclaration|ts.PropertyDeclaration| ts.PropertySignature, tc: ts.TypeChecker): boolean { if (!decl.type) return false; // Only properties with simple identifier names are candidates to treat as functions. if (!ts.isIdentifier(decl.name)) return false; let name = base.ident(decl.name); if (name.match(/^on[A-Z]/)) return false; return base.isFunctionType(decl.type, tc); } export default class DeclarationTranspiler extends base.TranspilerBase { private tc: ts.TypeChecker; private extendsClass = false; private visitPromises = false; private containsPromises = false; private promiseMembers: ts.SignatureDeclaration[] = []; static NUM_FAKE_REST_PARAMETERS = 5; setTypeChecker(tc: ts.TypeChecker) { this.tc = tc; } setFacadeConverter(fc: FacadeConverter) { this.fc = fc; } getJsPath(node: ts.Node, suppressUnneededPaths: boolean): string { const path: Array<String> = []; let moduleDecl = base.getAncestor(node, ts.SyntaxKind.ModuleDeclaration) as ts.ModuleDeclaration; while (moduleDecl != null) { path.unshift(moduleDecl.name.text); moduleDecl = base.getAncestor(moduleDecl.parent, ts.SyntaxKind.ModuleDeclaration) as ts.ModuleDeclaration; } let classDecl = base.getEnclosingClass(node); if (classDecl) { path.push(classDecl.name.text); } if (ts.isModuleDeclaration(node)) { path.push(base.getModuleName(node)); } else if (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)) { // Already handled by call to getEnclosingClass. } else if (ts.isEnumDeclaration(node)) { path.push(node.name.text); } else if ( ts.isPropertyDeclaration(node) || ts.isVariableDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node) || ts.isPropertySignature(node)) { let memberName = base.ident(node.name); if (!base.isStatic(node) && classDecl != null) return memberName; path.push(memberName); } else { throw 'Internal error. Unexpected node kind:' + ts.SyntaxKind[node.kind]; } if (suppressUnneededPaths && path.length === 1) { // No need to specify the path if is simply the node name or the escaped version of the node // name. return ''; } return path.join('.'); } private isAnonymous(node: ts.Node): boolean { if (ts.isInterfaceDeclaration(node)) { const extendedInterfaceDecl = node as base.ExtendedInterfaceDeclaration; // If we were able to associate a variable declaration with the interface definition then the // interface isn't actually anonymous. return !extendedInterfaceDecl.constructedType; } else if (this.trustJSTypes && ts.isClassLike(node)) { // If the trust-js-types flag is set, @anonymous tags are emitted on all classes that don't // have any constructors or any static members. const hasConstructor = node.members.some((member: ts.TypeElement|ts.ClassElement) => { return ts.isConstructorDeclaration(member) || ts.isConstructSignatureDeclaration(member); }); const hasStatic = node.members.some(base.isStatic); return !hasConstructor && !hasStatic; } return false; } maybeEmitJsAnnotation(node: ts.Node, {suppressUnneededPaths}: {suppressUnneededPaths: boolean}) { // No need to emit the annotations as an entity outside the code comment // will already have the same annotation. if (this.insideCodeComment) return; if (this.isAnonymous(node)) { this.emit('@anonymous'); this.emit('@JS()'); return; } const name = this.getJsPath(node, suppressUnneededPaths); this.emit('@JS('); if (name.length > 0) { this.emit(`"${name}"`); } this.emit(')'); } /** * Emit fake constructors to placate the Dart Analyzer for JS Interop classes. */ maybeEmitFakeConstructors(decl: ts.Node) { if (ts.isClassDeclaration(decl)) { // Required to avoid spurious dart errors involving base classes without // default constructors. this.emit('// @Ignore\n'); this.fc.visitTypeName(decl.name); this.emit('.fakeConstructor$()'); if (this.extendsClass) { // Required to keep the Dart Analyzer happy when a class has subclasses. this.emit(': super.fakeConstructor$()'); } this.emit(';\n'); } } private visitName(name: ts.PropertyName|ts.BindingName) { if (base.getEnclosingClass(name) != null) { this.visit(name); return; } // Have to rewrite names in this case as we could have conflicts due to needing to support // multiple JS modules in a single Dart module. if (!ts.isIdentifier(name)) { throw 'Internal error: unexpected function name kind:' + name.kind; } let entry = this.fc.lookupDartValueName(name); if (entry) { this.emit(entry.name); return; } this.visit(name); } private notSimpleBagOfProperties(type: ts.Type): boolean { if (this.tc.getSignaturesOfType(type, ts.SignatureKind.Call).length > 0) return true; if (this.tc.getSignaturesOfType(type, ts.SignatureKind.Construct).length > 0) return true; if (type.symbol) { let declaration = type.symbol.declarations.find(ts.isInterfaceDeclaration); // We have to check the actual declaration as if (declaration && declaration.members) { let members = declaration.members; for (let i = 0; i < members.length; ++i) { let node = members[i]; if (base.isStatic(node)) return true; switch (node.kind) { case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.VariableDeclaration: break; default: return true; } } } } return false; } /** * Returns whether all members of the class and all base classes are properties. */ hasOnlyProperties(decl: ts.InterfaceDeclaration, outProperties: ts.PropertyDeclaration[]): boolean { let type = <ts.InterfaceType>this.tc.getTypeAtLocation(decl); let symbols = this.tc.getPropertiesOfType(type); let baseTypes = this.tc.getBaseTypes(type); if (this.notSimpleBagOfProperties(type)) return false; for (let i = 0; i < baseTypes.length; ++i) { let baseType = baseTypes[i]; if (this.notSimpleBagOfProperties(baseType)) return false; } let properties: ts.Declaration[] = []; for (let i = 0; i < symbols.length; ++i) { let symbol = symbols[i]; let property = symbol.valueDeclaration; properties.push(property); } return this.hasOnlyPropertiesHelper(ts.createNodeArray(properties), outProperties); } hasOnlyPropertiesHelper( properties: ts.NodeArray<ts.Declaration>, outProperties: ts.Declaration[]): boolean { for (let i = 0; i < properties.length; ++i) { let node = properties[i]; if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isVariableDeclaration(node)) { if (this.promoteFunctionLikeMembers && isFunctionLikeProperty(node, this.tc)) { return false; } outProperties.push(node); } else { return false; } } return outProperties.length > 0; } visitClassBody(decl: base.ClassLike|ts.TypeLiteralNode, name: ts.Identifier) { let properties: ts.PropertyDeclaration[] = []; let isPropertyBag = false; if (ts.isInterfaceDeclaration(decl)) { const extendedInterfaceDecl = decl as base.ExtendedInterfaceDeclaration; const constructedType = extendedInterfaceDecl.constructedType; if (constructedType) { // If this interface is the upgraded version of a variable whose type contained a // constructor, we must check the type hierarchy of the original type, as well as the // properties of the new merged interface. if (ts.isInterfaceDeclaration(constructedType)) { isPropertyBag = this.hasOnlyProperties(constructedType, properties) && this.hasOnlyPropertiesHelper(decl.members, properties); } else if (ts.isTypeLiteralNode(constructedType)) { isPropertyBag = this.hasOnlyPropertiesHelper(decl.members, properties); } } else { isPropertyBag = this.hasOnlyProperties(decl, properties); } } else if (ts.isTypeLiteralNode(decl)) { isPropertyBag = this.hasOnlyPropertiesHelper(decl.members, properties); } this.visitMergingOverloads(decl.members); if (isPropertyBag) { const propertiesWithValidNames = properties.filter((p) => { return isValidIdentifier(p.name); }); this.emit('external factory'); this.fc.visitTypeName(name); if (propertiesWithValidNames.length) { this.emitNoSpace('({'); for (let i = 0; i < propertiesWithValidNames.length; i++) { if (i > 0) this.emitNoSpace(','); let p = propertiesWithValidNames[i]; this.visit(p.type); this.visit(p.name); } this.emitNoSpace('});'); } else { this.emitNoSpace('();'); } } } /** * Visits an array of class members and merges overloads. * * @returns An updated version of the members array. All overloaded methods are grouped into * MergedMember objects that contain all original declarations, as well as the merged result. * Other non-overloaded members are represented by MergedMembers with only one constituent, * which is the single declaration of the member. */ visitMergingOverloads(members: ts.NodeArray<ts.Node>): MergedMember[] { const result: MergedMember[] = []; // TODO(jacobr): merge method overloads. let groups: Map<string, ts.Node[]> = new Map(); let orderedGroups: Array<ts.Node[]> = []; members.forEach((node) => { let name = ''; switch (node.kind) { case ts.SyntaxKind.Block: // For JS interop we always skip the contents of a block. break; case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.VariableDeclaration: { let propertyDecl = <ts.PropertyDeclaration|ts.VariableDeclaration>node; // We need to emit these as properties not fields. if (!this.promoteFunctionLikeMembers || !isFunctionLikeProperty(propertyDecl, this.tc)) { // Suppress the prototype member if (base.ident(propertyDecl.name) === 'prototype') { return; } orderedGroups.push([node]); return; } // Convert to a Method. let type = propertyDecl.type; let funcDecl = <ts.FunctionLikeDeclaration>ts.createNode(ts.SyntaxKind.MethodDeclaration); funcDecl.parent = node.parent; funcDecl.name = propertyDecl.name as ts.Identifier; switch (type.kind) { case ts.SyntaxKind.FunctionType: let callSignature = <ts.SignatureDeclaration>(<ts.Node>type); funcDecl.parameters = <ts.NodeArray<ts.ParameterDeclaration>>callSignature.parameters; funcDecl.type = callSignature.type; // Fall through to the function case using this node node = funcDecl; break; case ts.SyntaxKind.UnionType: case ts.SyntaxKind.TypeLiteral: throw 'Not supported yet'; default: throw 'Unexpected case'; } name = base.ident((<ts.FunctionLikeDeclaration>node).name); } break; case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.FunctionExpression: name = base.ident((<ts.FunctionLikeDeclaration>node).name); break; case ts.SyntaxKind.CallSignature: name = 'call'; break; case ts.SyntaxKind.Constructor: break; case ts.SyntaxKind.ConstructSignature: break; case ts.SyntaxKind.IndexSignature: name = '[]'; break; default: // Create a group with a single entry as merging is not required for this node kind. orderedGroups.push([node]); return; } let group: Array<ts.Node>; if (groups.has(name)) { group = groups.get(name); } else { group = []; groups.set(name, group); orderedGroups.push(group); } group.push(node); }); orderedGroups.forEach((group: Array<ts.SignatureDeclaration>) => { const first = group[0]; // If the members in this group are Promise properties or Promise-returning methods and // this.visitPromises is false, skip visiting these members and add them to // this.promiseMembers. If the members in this group are/return Promises and // this.visitPromises is true, it means that this function is being called from // emitMembersAsExtensions and the members should now be visited. if (!this.visitPromises && base.isPromise(first.type)) { if (!this.containsPromises) { this.containsPromises = true; } group.forEach((declaration: ts.SignatureDeclaration) => { this.promiseMembers.push(declaration); }); return; } if (group.length === 1) { this.visit(first); result.push(new MergedMember(group, first)); return; } group.forEach((fn: ts.Node) => { // Emit overrides in a comment that the Dart analyzer can at some point // use to improve autocomplete. this.maybeLineBreak(); this.enterCodeComment(); this.visit(fn); this.exitCodeComment(); this.maybeLineBreak(); }); // TODO: actually merge. let kind = first.kind; let merged = <ts.SignatureDeclaration>ts.createNode(kind); merged.parent = first.parent; base.copyLocation(first, merged); switch (kind) { case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.FunctionExpression: let fn = <ts.FunctionLikeDeclaration>first; merged.name = fn.name; break; case ts.SyntaxKind.CallSignature: break; case ts.SyntaxKind.Constructor: break; case ts.SyntaxKind.ConstructSignature: break; case ts.SyntaxKind.IndexSignature: break; default: throw 'Unexpected kind:' + kind; } let mergedParams = first.parameters.map( (param: ts.ParameterDeclaration) => new MergedParameter(param, this.fc)); let mergedType = new MergedType(this.fc); mergedType.merge(first.type); let mergedTypeParams = new MergedTypeParameters(this.fc); mergedTypeParams.merge(first.typeParameters); for (let i = 1; i < group.length; ++i) { let signature = <ts.SignatureDeclaration>group[i]; mergedType.merge(signature.type); mergedTypeParams.merge(signature.typeParameters); let overlap = Math.min(signature.parameters.length, mergedParams.length); for (let j = 0; j < overlap; ++j) { mergedParams[j].merge(signature.parameters[j]); } for (let j = overlap; j < mergedParams.length; ++j) { mergedParams[j].setOptional(); } for (let j = mergedParams.length; j < signature.parameters.length; ++j) { let param = new MergedParameter(signature.parameters[j], this.fc); param.setOptional(); mergedParams.push(param); } } merged.parameters = ts.createNodeArray(mergedParams.map((p) => p.toParameterDeclaration())); merged.type = mergedType.toTypeNode(); merged.typeParameters = mergedTypeParams.toTypeParameters(); this.fc.visit(merged); result.push(new MergedMember(group, merged)); }); return result; } constructor( tr: Transpiler, private fc: FacadeConverter, private enforceUnderscoreConventions: boolean, private promoteFunctionLikeMembers: boolean, private trustJSTypes: boolean) { super(tr); } visitNode(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.ModuleDeclaration: const moduleDecl = <ts.ModuleDeclaration>node; const moduleName = base.getModuleName(moduleDecl); const moduleBlock = base.getModuleBlock(moduleDecl); if (moduleName.startsWith('..')) { this.emit( '\n// Library augmentation not allowed by Dart. Ignoring augmentation of ' + moduleDecl.name.text + '\n'); break; } this.emit('\n// Module ' + moduleName + '\n'); this.visit(moduleBlock); this.emit('\n// End module ' + moduleName + '\n'); break; case ts.SyntaxKind.ExportKeyword: // TODO(jacobr): perhaps add a specific Dart annotation to indicate // exported members or provide a flag to only generate code for exported // members. break; case ts.SyntaxKind.EnumDeclaration: { let decl = <ts.EnumDeclaration>node; // The only legal modifier for an enum decl is const. let isConst = this.hasModifierFlag(decl, ts.ModifierFlags.Const); if (isConst) { this.reportError(node, 'const enums are not supported'); } // In JS interop mode we have to treat enums as JavaScript classes // with static members for each enum constant instead of as first // class enums. this.maybeEmitJsAnnotation(decl, {suppressUnneededPaths: true}); this.emit('class'); this.emit(decl.name.text); this.emit('{'); let nodes = decl.members; for (let i = 0; i < nodes.length; i++) { this.emit('external static num get'); this.visit(nodes[i]); this.emitNoSpace(';'); } this.emit('}'); } break; case ts.SyntaxKind.Parameter: { let paramDecl = <ts.ParameterDeclaration>node; if (paramDecl.type && paramDecl.type.kind === ts.SyntaxKind.FunctionType) { // Dart uses "returnType paramName ( parameters )" syntax. let fnType = <ts.FunctionOrConstructorTypeNode>paramDecl.type; let hasRestParameter = fnType.parameters.some(p => !!p.dotDotDotToken); if (!hasRestParameter) { // Dart does not support rest parameters/varargs, degenerate to just "Function". // TODO(jacobr): also consider faking 0 - NUM_FAKE_REST_PARAMETERS // instead. this.visit(fnType.type); this.visit(paramDecl.name); this.visitParameters(fnType.parameters, {namesOnly: false}); break; } } if (paramDecl.dotDotDotToken) { // Weak support of varargs that works ok if you have 5 of fewer args. let paramType: ts.TypeNode; let type = paramDecl.type; if (type) { if (ts.isArrayTypeNode(type)) { paramType = type.elementType; } else if (type.kind !== ts.SyntaxKind.AnyKeyword) { console.error('Warning: falling back to dynamic for varArgs type: ' + type.getText()); } } for (let i = 1; i <= DeclarationTranspiler.NUM_FAKE_REST_PARAMETERS; ++i) { if (i > 1) { this.emitNoSpace(','); } this.visit(paramType); this.emit(base.ident(paramDecl.name) + i); } break; } // TODO(jacobr): should we support if (paramDecl.name.kind === ts.SyntaxKind.ObjectBindingPattern) { this.emit('Object'); let pattern = paramDecl.name as ts.ObjectBindingPattern; let elements = pattern.elements; let name = elements.map((e) => base.ident(e.name)).join('_'); // Warning: this name is unlikely to but could possible overlap with // other parameter names. this.emit(name); this.enterCodeComment(); this.emit(pattern.getText()); this.exitCodeComment(); break; } if (paramDecl.name.kind !== ts.SyntaxKind.Identifier) { throw 'Unsupported parameter name kind: ' + paramDecl.name.kind; } this.visit(paramDecl.type); this.visit(paramDecl.name); } break; case ts.SyntaxKind.EnumMember: { let member = <ts.EnumMember>node; this.visit(member.name); } break; case ts.SyntaxKind.SourceFile: let sourceFile = node as ts.SourceFile; this.visitMergingOverloads(sourceFile.statements); if (this.containsPromises) { this.addImport('package:js/js_util.dart', 'promiseToFuture'); // TODO(derekx): Move this definition of the Promise class to a package this.emit(`@JS() abstract class Promise<T> { external factory Promise(void executor(void resolve(T result), Function reject)); external Promise then(void onFulfilled(T result), [Function onRejected]); }\n`); } break; case ts.SyntaxKind.ModuleBlock: { let block = <ts.ModuleBlock>node; this.visitMergingOverloads(block.statements); } break; case ts.SyntaxKind.VariableDeclarationList: { // We have to handle variable declaration lists differently in the case // of JS interop because Dart does not support external variables. let varDeclList = <ts.VariableDeclarationList>node; this.visitList(varDeclList.declarations, ' '); } break; case ts.SyntaxKind.VariableDeclaration: { // We have to handle variable declarations differently in the case of JS // interop because Dart does not support external variables. let varDecl = <ts.VariableDeclaration>node; this.emitProperty({ mode: emitPropertyMode.getter, declaration: varDecl, emitJsAnnotation: true, isExternal: true }); if (!this.hasNodeFlag(varDecl, ts.NodeFlags.Const)) { this.emitProperty({ mode: emitPropertyMode.setter, declaration: varDecl, emitJsAnnotation: true, isExternal: true }); } } break; case ts.SyntaxKind.CallSignature: { let fn = <ts.SignatureDeclaration>node; this.emit('external'); this.visit(fn.type); this.emit('call'); this.visitParameters(fn.parameters, {namesOnly: false}); this.emitNoSpace(';'); } break; case ts.SyntaxKind.IndexSignature: this.emit('/* Index signature is not yet supported by JavaScript interop. */\n'); break; case ts.SyntaxKind.ExportAssignment: // let exportAssignment = <ts.ExportAssignment>node; this.emit('/* WARNING: export assignment not yet supported. */\n'); break; case ts.SyntaxKind.TypeAliasDeclaration: { const alias = <ts.TypeAliasDeclaration>node; const type = alias.type; if (ts.isTypeLiteralNode(type)) { // Object literal type alias declarations can be treated like interface declarations. const literal = type; this.emit('@anonymous\n@JS()\n'); this.visitClassLikeHelper( 'abstract class', literal, alias.name, alias.typeParameters, null); } else if (ts.isFunctionTypeNode(type)) { // Function type alias definitions are equivalent to dart typedefs. this.visitFunctionTypedefInterface(base.ident(alias.name), type, alias.typeParameters); } else { this.enterCodeComment(); if (ts.isMappedTypeNode(alias.type)) { this.emitNoSpace('\n'); this.emit( 'Warning: Mapped types are not supported in Dart. Uses of this type will be replaced by dynamic.'); this.emitNoSpace('\n'); } else if (ts.isConditionalTypeNode(alias.type)) { this.emit( 'Warning: Conditional types are not supported in Dart. Uses of this type will be replaced by dynamic.'); this.emitNoSpace('\n'); } this.emitNoSpace(alias.getText()); this.emitNoSpace('\n'); this.exitCodeComment(); this.emitNoSpace('\n'); } // We ignore other type alias declarations as Dart doesn't have a corresponding feature yet. } break; case ts.SyntaxKind.ClassDeclaration: case ts.SyntaxKind.InterfaceDeclaration: { this.extendsClass = false; let classDecl = <ts.ClassDeclaration|ts.InterfaceDeclaration>node; let isInterface = node.kind === ts.SyntaxKind.InterfaceDeclaration; if (isInterface && base.isFunctionTypedefLikeInterface(classDecl as ts.InterfaceDeclaration)) { let member = <ts.CallSignatureDeclaration>classDecl.members[0]; this.visitFunctionTypedefInterface(classDecl.name.text, member, classDecl.typeParameters); break; } let customName = this.fc.lookupCustomDartTypeName(classDecl.name); if (customName && !customName.keep) { this.emit('\n/* Skipping class ' + base.ident(classDecl.name) + '*/\n'); break; } this.maybeEmitJsAnnotation(node, {suppressUnneededPaths: true}); if (isInterface || this.hasModifierFlag(classDecl, ts.ModifierFlags.Abstract)) { this.visitClassLike('abstract class', classDecl); } else { this.visitClassLike('class', classDecl); } } break; case ts.SyntaxKind.HeritageClause: { let heritageClause = <ts.HeritageClause>node; if (base.isExtendsClause(<ts.HeritageClause>heritageClause)) { this.extendsClass = true; } if (base.isExtendsClause(heritageClause)) { this.emit('extends'); } else { this.emit('implements'); } // Can only have one member for extends clauses. this.visitList(heritageClause.types); } break; case ts.SyntaxKind.ExpressionWithTypeArguments: { let exprWithTypeArgs = <ts.ExpressionWithTypeArguments>node; let expr = exprWithTypeArgs.expression; if (ts.isIdentifier(expr) || ts.isQualifiedName(expr) || ts.isPropertyAccessExpression(expr)) { this.fc.visitTypeName(expr); } else { this.visit(expr); } this.maybeVisitTypeArguments(exprWithTypeArgs); } break; case ts.SyntaxKind.Constructor: case ts.SyntaxKind.ConstructSignature: { const ctorDecl = <ts.ConstructorDeclaration>node; if (ts.isTypeLiteralNode(node.parent)) { // All constructors within TypeLiteralNodes should have been merged into corresponding // classes. The only exception is this case, where there exist aliases to those literals. this.emit('// Skipping constructor from aliased type.\n'); this.enterCodeComment(); this.emit('new'); this.visitParameters(ctorDecl.parameters, {namesOnly: false}); this.emitNoSpace(';'); this.exitCodeComment(); break; } // Find containing class name. let classDecl = base.getEnclosingClass(ctorDecl); if (!classDecl) this.reportError(ctorDecl, 'cannot find outer class node'); const isAnonymous = this.isAnonymous(classDecl); if (isAnonymous) { this.emit('// Constructors on anonymous interfaces are not yet supported.\n'); this.enterCodeComment(); } this.visitDeclarationMetadata(ctorDecl); this.fc.visitTypeName(classDecl.name); this.visitParameters(ctorDecl.parameters, {namesOnly: false}); this.emitNoSpace(';'); if (isAnonymous) { this.exitCodeComment(); this.emit('\n'); } } break; case ts.SyntaxKind.PropertyDeclaration: this.visitProperty(<ts.PropertyDeclaration>node); break; case ts.SyntaxKind.SemicolonClassElement: // No-op, don't emit useless declarations. break; case ts.SyntaxKind.MethodDeclaration: this.visitDeclarationMetadata(<ts.MethodDeclaration>node); this.visitFunctionLike(<ts.MethodDeclaration>node); break; case ts.SyntaxKind.GetAccessor: this.visitDeclarationMetadata(<ts.MethodDeclaration>node); this.visitFunctionLike(<ts.AccessorDeclaration>node, 'get'); break; case ts.SyntaxKind.SetAccessor: this.visitDeclarationMetadata(<ts.MethodDeclaration>node); this.visitFunctionLike(<ts.AccessorDeclaration>node, 'set'); break; case ts.SyntaxKind.FunctionDeclaration: let funcDecl = <ts.FunctionDeclaration>node; this.visitDeclarationMetadata(funcDecl); this.visitFunctionLike(funcDecl); break; case ts.SyntaxKind.FunctionExpression: let funcExpr = <ts.FunctionExpression>node; this.visitFunctionLike(funcExpr); break; case ts.SyntaxKind.PropertySignature: let propSig = <ts.PropertyDeclaration>node; this.visitProperty(propSig); break; case ts.SyntaxKind.MethodSignature: let methodSignatureDecl = <ts.FunctionLikeDeclaration>node; this.visitDeclarationMetadata(methodSignatureDecl); this.visitFunctionLike(methodSignatureDecl); break; case ts.SyntaxKind.StaticKeyword: // n-op, handled in `visitFunctionLike` and `visitProperty` below. break; case ts.SyntaxKind.AbstractKeyword: // Abstract methods in Dart simply lack implementation, // and don't use the 'abstract' modifier // Abstract classes are handled in `case ts.SyntaxKind.ClassDeclaration` above. break; case ts.SyntaxKind.PrivateKeyword: // no-op, handled through '_' naming convention in Dart. break; case ts.SyntaxKind.PublicKeyword: // Handled in `visitDeclarationMetadata` below. break; case ts.SyntaxKind.ProtectedKeyword: // Handled in `visitDeclarationMetadata` below. break; case ts.SyntaxKind.DeclareKeyword: // In an ambient top level declaration like "declare var" or "declare function", the declare // keyword is stored as a modifier but we don't need to handle it. The JS interop code that // needs to be emitted to access these variables or functions is the same regardless of // whether they are declared in a .d.ts file or a .ts file. // "declare var x" or "export var x" in a .d.ts file is handled the same way as "var x" in a // .ts file break; case ts.SyntaxKind.VariableStatement: let variableStmt = <ts.VariableStatement>node; this.visit(variableStmt.declarationList); break; case ts.SyntaxKind.SwitchStatement: case ts.SyntaxKind.ArrayLiteralExpression: case ts.SyntaxKind.ExpressionStatement: case ts.SyntaxKind.EmptyStatement: // No need to emit anything for these cases. break; default: return false; } return true; } private visitFunctionLike(fn: ts.FunctionLikeDeclaration, accessor?: string) { this.fc.pushTypeParameterNames(fn); if (base.isStatic(fn)) { this.emit('static'); } try { this.visit(fn.type); if (accessor) this.emit(accessor); let name = fn.name; if (name) { if (name.kind !== ts.SyntaxKind.Identifier) { this.reportError(name, 'Unexpected name kind:' + name.kind); } this.visitName(name); } if (fn.typeParameters && fn.typeParameters.length > 0) { let insideComment = this.insideCodeComment; if (!insideComment) { this.enterCodeComment(); } this.emitNoSpace('<'); this.enterTypeArguments(); this.visitList(fn.typeParameters); this.exitTypeArguments(); this.emitNoSpace('>'); if (!insideComment) { this.exitCodeComment(); } } // Dart does not even allow the parens of an empty param list on getter if (accessor !== 'get') { this.visitParameters(fn.parameters, {namesOnly: false}); } else { if (fn.parameters && fn.parameters.length > 0) { this.reportError(fn, 'getter should not accept parameters'); } } this.emitNoSpace(';'); } finally { this.fc.popTypeParameterNames(fn); } } /** * Visit a property declaration. * In the special case of property parameters in a constructor, we also allow * a parameter to be emitted as a property. * We have to emit properties as getter setter pairs as Dart does not support * external fields. * In the special case of property parameters in a constructor, we also allow a parameter to be * emitted as a property. */ private visitProperty( decl: ts.PropertyDeclaration|ts.ParameterDeclaration, isParameter?: boolean) { // Check if the name contains special characters other than $ and _ const canBeRenamed = identifierCanBeRenamed(decl.name); // TODO(derekx): Properties with names that contain special characters other than _ and $ are // currently ignored by commenting them out. We should determine a way to rename these // properties using extension members in the future. this.maybeWrapInCodeComment({shouldWrap: !canBeRenamed, newLine: true}, () => { this.emitProperty({ mode: emitPropertyMode.getter, declaration: decl, emitJsAnnotation: false, isExternal: true }); }); if (!base.isReadonly(decl)) { this.maybeWrapInCodeComment({shouldWrap: !canBeRenamed, newLine: true}, () => { this.emitProperty({ mode: emitPropertyMode.setter, declaration: decl, emitJsAnnotation: false, isExternal: true }); }); } } private visitClassLike(keyword: string, decl: base.ClassLike) { return this.visitClassLikeHelper( keyword, decl, decl.name, decl.typeParameters, decl.heritageClauses); } /** * Helper that generates a Dart class definition. * The definition of the TypeScript structure we are generating a Dart class facade for is broken * down into parts so that we can support all the various ways TypeScript can define a structure * that should generate a Dart class. */ private visitClassLikeHelper( keyword: string, decl: base.ClassLike|ts.TypeLiteralNode, name: ts.Identifier, typeParameters: ts.NodeArray<ts.TypeParameterDeclaration>, heritageClauses: ts.NodeArray<ts.HeritageClause>) { this.emit(keyword); this.visitClassLikeName(name, typeParameters, heritageClauses, false); this.emit('{'); this.maybeEmitFakeConstructors(decl); // Synthesize explicit properties for ctor with 'property parameters' let synthesizePropertyParam = (param: ts.ParameterDeclaration) => { if (this.hasModifierFlag(param, ts.ModifierFlags.Public) || this.hasModifierFlag(param, ts.ModifierFlags.Private) || this.hasModifierFlag(param, ts.ModifierFlags.Protected)) { // TODO: we should enforce the underscore prefix on privates this.visitProperty(param, true); } }; (decl.members as ts.NodeArray<ts.Declaration>) .filter(base.isConstructor) .forEach( (ctor) => (<ts.ConstructorDeclaration>ctor).parameters.forEach(synthesizePropertyParam)); this.visitClassBody(decl, name); this.emit('}\n'); if (this.promiseMembers.length) { const visitName = () => { this.visitClassLikeName(name, typeParameters, ts.createNodeArray(), false); }; const visitNameOfExtensions = () => { this.visitClassLikeName(name, typeParameters, ts.createNodeArray(), true); }; this.emitMembersAsExtensions(decl, visitName, visitNameOfExtensions, this.promiseMembers); this.promiseMembers = []; } this.emit('\n'); } private visitClassLikeName( name: ts.Identifier, typeParameters: ts.NodeArray<ts.TypeParameterDeclaration>, heritageClauses: ts.NodeArray<ts.HeritageClause>, extension: boolean) { this.fc.visitTypeName(name); if (extension) { this.emitNoSpace('Extensions'); } if (typeParameters && typeParameters.length > 0) { this.emit('<'); this.enterTypeArguments(); this.visitList(typeParameters); this.exitTypeArguments(); this.emit('>'); } this.visitEachIfPresent(heritageClauses); } private visitDeclarationMetadata(decl: ts.Declaration) { this.visitEachIfPresent(decl.modifiers); switch (decl.kind) { case ts.SyntaxKind.Constructor: case ts.SyntaxKind.ConstructSignature: this.emit('external factory'); break; case ts.SyntaxKind.ArrowFunction: case ts.SyntaxKind.CallSignature: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.PropertySignature: case ts.SyntaxKind.FunctionDeclaration: if (!base.getEnclosingClass(decl)) { this.maybeEmitJsAnnotation(decl, {suppressUnneededPaths: true}); } this.emit('external'); break; default: throw 'Unexpected declaration kind:' + decl.kind; } } /** * Handles a function typedef-like interface, i.e. an interface that only declares a single * call signature, by translating to a Dart `typedef`. */ private visitFunctionTypedefInterface( name: string, signature: ts.SignatureDeclaration, typeParameters: ts.NodeArray<ts.TypeParameterDeclaration>) { this.emit('typedef'); if (signature.type) { this.visit(signature.type); } this.emit(name); if (typeParameters) { this.emitNoSpace('<'); this.enterTypeArguments(); this.visitList(typeParameters); this.exitTypeArguments(); this.emitNoSpace('>'); } this.visitParameters(signature.parameters, {namesOnly: false}); this.emitNoSpace(';'); } private emitProperty({mode, declaration, emitJsAnnotation, isExternal, emitBody}: emitPropertyOptions) { const {name, type} = declaration; if (emitJsAnnotation) { this.maybeEmitJsAnnotation(declaration, {suppressUnneededPaths: true}); } if (isExternal) { this.emit('external'); } if (base.isStatic(declaration)) { this.emit('static'); } if (mode === emitPropertyMode.getter) { this.visit(type); this.emit('get'); this.visitName(name); } else if (mode === emitPropertyMode.setter) { this.emit('set'); this.visitName(name); this.emitNoSpace('('); this.visit(type); this.emit('v)'); } if (emitBody && !ts.isVariableDeclaration(declaration) && !ts.isParameter(declaration)) { this.emit('{'); emitBody(declaration); this.emit('}'); } else { this.emitNoSpace(';'); } } private emitCastThisToPrivateClass(visitClassName: () => void) { this.emit('final Object t = this;'); this.emit('final _'); visitClassName(); this.emit('tt = t;\n'); } private emitMembersAsExtensions( classDecl: ts.ObjectTypeDeclaration, visitClassName: () => void, visitNameOfExtensions: () => void, methods: ts.SignatureDeclaration[]) { this.visitPromises = true; this.fc.emitPromisesAsFutures = false; // Emit private class containing external methods this.maybeEmitJsAnnotation(classDecl, {suppressUnneededPaths: false}); this.emit(`abstract class _`); visitClassName(); this.emit('{'); const mergedMembers = this.visitMergingOverloads(ts.createNodeArray(Array.from(methods))); this.emit('}\n'); this.fc.emitPromisesAsFutures = true; // Emit extensions on public class to expose methods this.emit('extension'); visitNameOfExtensions(); this.emit('on'); visitClassName(); this.emit('{'); for (const merged of mergedMembers) { const declaration = merged.mergedDeclaration; if (ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration)) { this.emitProperty({ mode: emitPropertyMode.getter, declaration, emitJsAnnotation: false, isExternal: false, emitBody: () => { this.emitCastThisToPrivateClass(visitClassName); this.emitExtensionGetterBody(declaration); } }); if (!base.isReadonly(declaration)) { this.emitProperty({ mode: emitPropertyMode.setter, declaration, emitJsAnnotation: false, isExternal: false, emitBody: () => { this.emitCastThisToPrivateClass(visitClassName); this.emitExtensionSetterBody(declaration); } }); } } else if (ts.isMethodDeclaration(declaration) || ts.isMethodSignature(declaration)) { this.visit(declaration.type); this.visitName(declaration.name); this.visitParameters(declaration.parameters, {namesOnly: false}); this.emit('{'); this.emitCastThisToPrivateClass(visitClassName); this.emitExtensionMethodBody(merged); this.emit('}\n'); } } this.emit('}\n'); this.visitPromises = false; } private emitExtensionMethodBody({constituents, mergedDeclaration}: MergedMember) { // Determine all valid arties of this method by going through the overloaded signatures const arities: Set<number> = new Set(); for (const constituent of constituents) { const arity = constituent.parameters.length; arities.add(arity); } const sortedArities = Array.from(arities).sort(); for (const arity of sortedArities) { if (arity < mergedDeclaration.parameters.length) { const firstOptionalIndex = arity; const suppliedParameters = mergedDeclaration.parameters.slice(0, firstOptionalIndex); const omittedParameters = mergedDeclaration.parameters.slice( firstOptionalIndex, mergedDeclaration.parameters.length); // Emit null checks to verify the number of omitted parameters this.emit('if ('); let isFirst = true; for (const omitted of omittedParameters) { if (isFirst) { isFirst = false; } else { this.emit('&&'); } this.visit(omitted.name); this.emit('== null'); } this.emit(') {'); this.emit('return promiseToFuture('); this.emit(PRIVATE_CLASS_INSTANCE_IN_EXTENSIONS); this.emit('.'); this.visitName(mergedDeclaration.name); this.visitParameters(ts.createNodeArray(suppliedParameters), {namesOnly: true}); this.emit('); }\n'); } else { // No parameters were omitted, no null checks are necessary for this call this.emit('return promiseToFuture('); this.emit(PRIVATE_CLASS_INSTANCE_IN_EXTENSIONS); this.emit('.'); this.visitName(mergedDeclaration.name); this.visitParameters(ts.createNodeArray(mergedDeclaration.parameters), {namesOnly: true}); this.emit(');\n'); } } } private emitExtensionGetterBody(declaration: ts.PropertyDeclaration|ts.PropertySignature) { this.emit('return promiseToFuture('); this.emit(PRIVATE_CLASS_INSTANCE_IN_EXTENSIONS); this.emit('.'); this.visitName(declaration.name); this.emit(');'); } private emitExtensionSetterBody(declaration: ts.PropertyDeclaration|ts.PropertySignature) { this.emit(PRIVATE_CLASS_INSTANCE_IN_EXTENSIONS); this.emit('.'); this.visitName(declaration.name); this.emit('='); // To emit the call to the Promise constructor, we need to temporarily disable // this.fc.emitPromisesAsFutures this.fc.emitPromisesAsFutures = false; this.visit(declaration.type); this.fc.emitPromisesAsFutures = true; this.emit('(allowInterop((resolve, reject) { v.then(resolve, onError: reject); }));'); } }
the_stack
import React from 'react'; import styled from '@emotion/styled'; import { keyframes } from '@emotion/core'; import configureCadence, { CADENCE_LANGUAGE_ID } from '../util/cadence'; import { CadenceCheckCompleted, CadenceLanguageServer, Callbacks, } from '../util/language-server'; import { createCadenceLanguageClient } from '../util/language-client'; import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import { EntityType } from 'providers/Project'; import Arguments from 'components/Arguments'; import { Argument } from 'components/Arguments/types'; import { CadenceProblem, formatMarker, goTo, Highlight, ProblemsList, } from '../util/language-syntax-errors'; import { MonacoLanguageClient, ExecuteCommandRequest, } from 'monaco-languageclient'; const { MonacoServices } = require('monaco-languageclient/lib/monaco-services'); const blink = keyframes` 50% { opacity: 0.5; } `; const EditorContainer = styled.div` width: 100%; height: 100%; position: relative; .drag-box { width: fit-content; height: fit-content; position: absolute; right: 30px; top: 0; z-index: 12; } .constraints { width: 96vw; height: 90vh; position: fixed; left: 2vw; right: 2vw; top: 2vw; bottom: 2vw; pointer-events: none; } .playground-syntax-error-hover { background-color: rgba(238, 67, 30, 0.1); } .playground-syntax-error-hover-selection { background-color: rgba(238, 67, 30, 0.3); border-radius: 3px; animation: ${blink} 1s ease-in-out infinite; } .playground-syntax-warning-hover { background-color: rgb(238, 169, 30, 0.1); } .playground-syntax-warning-hover-selection { background-color: rgb(238, 169, 30, 0.3); border-radius: 3px; animation: ${blink} 1s ease-in-out infinite; } .playground-syntax-info-hover { background-color: rgb(85, 238, 30, 0.1); } .playground-syntax-info-hover-selection { background-color: rgb(85, 238, 30, 0.3); border-radius: 3px; animation: ${blink} 1s ease-in-out infinite; } .playground-syntax-hint-hover, .playground-syntax-unknown-hover { background-color: rgb(160, 160, 160, 0.1); } .playground-syntax-hint-hover-selection, .playground-syntax-unknown-hover-selection { background-color: rgb(160, 160, 160, 0.3); border-radius: 3px; animation: ${blink} 1s ease-in-out infinite; } `; type EditorState = { model: any; viewState: any; }; let monacoServicesInstalled = false; type CodeGetter = (index: number) => string | undefined; type CadenceEditorProps = { code: string; mount: string; onChange: any; activeId: string; type: EntityType; getCode: CodeGetter; }; type CadenceEditorState = { args: { [key: string]: Argument[] }; problems: { [key: string]: ProblemsList }; }; class CadenceEditor extends React.Component< CadenceEditorProps, CadenceEditorState > { editor: monaco.editor.ICodeEditor; languageClient?: MonacoLanguageClient; _subscription: any; editorStates: { [key: string]: EditorState }; private callbacks: Callbacks; constructor(props: { code: string; mount: string; onChange: any; activeId: string; type: EntityType; getCode: CodeGetter; }) { super(props); this.editorStates = {}; this.handleResize = this.handleResize.bind(this); window.addEventListener('resize', this.handleResize); configureCadence(); this.state = { args: {}, problems: {}, }; } handleResize() { this.editor && this.editor.layout(); } async componentDidMount() { const editor = monaco.editor.create( document.getElementById(this.props.mount), { theme: 'vs-light', language: CADENCE_LANGUAGE_ID, minimap: { enabled: false, }, }, ); this.editor = editor; this._subscription = this.editor.onDidChangeModelContent((event: any) => { this.props.onChange(this.editor.getValue(), event); }); const state = this.getOrCreateEditorState( this.props.activeId, this.props.code, ); this.editor.setModel(state.model); this.editor.focus(); if (this.props.activeId && !this.callbacks) { const getCode = (index: number) => this.props.getCode(index) await this.loadLanguageServer(getCode); } } private async loadLanguageServer( getCode: CodeGetter, ) { this.callbacks = { // The actual callback will be set as soon as the language server is initialized toServer: null, // The actual callback will be set as soon as the language server is initialized onClientClose: null, // The actual callback will be set as soon as the language client is initialized onServerClose: null, // The actual callback will be set as soon as the language client is initialized toClient: null, getAddressCode(address: string): string | undefined { const number = parseInt(address, 16); if (!number) { return; } return getCode(number - 1); }, }; // The Monaco Language Client services have to be installed globally, once. // An editor must be passed, which is only used for commands. // As the Cadence language server is not providing any commands this is OK if (!monacoServicesInstalled) { monacoServicesInstalled = true; MonacoServices.install(monaco); } // Start one language server per editor. // Even though one language server can handle multiple documents, // this demonstrates this is possible and is more resilient: // if the server for one editor crashes, it does not break the other editors await CadenceLanguageServer.create(this.callbacks); this.languageClient = createCadenceLanguageClient(this.callbacks); this.languageClient.start(); this.languageClient.onReady().then(() => { this.languageClient.onNotification( CadenceCheckCompleted.methodName, async (result: CadenceCheckCompleted.Params) => { if (result.valid) { const params = await this.getParameters(); this.setExecutionArguments(params); } this.processMarkers(); }, ); }); } private async getParameters() { await this.languageClient.onReady(); try { const args = await this.languageClient.sendRequest( ExecuteCommandRequest.type, { command: 'cadence.server.getEntryPointParameters', arguments: [this.editor.getModel().uri.toString()], }, ); return args || []; } catch (error) { console.error(error); } } processMarkers() { const model = this.editor.getModel(); const modelMarkers = monaco.editor.getModelMarkers({ resource: model.uri }); const errors = modelMarkers.reduce( (acc: { [key: string]: CadenceProblem[] }, marker) => { const mappedMarker: CadenceProblem = formatMarker(marker); acc[mappedMarker.type].push(mappedMarker); return acc; }, { error: [], warning: [], info: [], hint: [], }, ); const { activeId } = this.props; this.setState({ problems: { [activeId]: errors, }, }); } setExecutionArguments(args: Argument[]) { const { activeId } = this.props; this.setState({ args: { [activeId]: args, }, }); } getOrCreateEditorState(id: string, code: string): EditorState { const existingState = this.editorStates[id]; if (existingState !== undefined) { return existingState; } const model = monaco.editor.createModel(code, CADENCE_LANGUAGE_ID); const state: EditorState = { model, viewState: null, }; this.editorStates[id] = state; return state; } saveEditorState(id: string, viewState: any) { this.editorStates[id].viewState = viewState; } switchEditor(prevId: string, newId: string) { const newState = this.getOrCreateEditorState(newId, this.props.code); const currentViewState = this.editor.saveViewState(); this.saveEditorState(prevId, currentViewState); this.editor.setModel(newState.model); this.editor.restoreViewState(newState.viewState); this.editor.focus(); } componentWillUnmount() { this.destroyMonaco(); window.removeEventListener('resize', this.handleResize); if (this.callbacks && this.callbacks.onClientClose) { this.callbacks.onClientClose(); } } async componentDidUpdate(prevProps: any) { if (this.props.activeId !== prevProps.activeId) { this.switchEditor(prevProps.activeId, this.props.activeId); this.destroyMonaco(); await this.componentDidMount(); } } destroyMonaco() { if (this.editor) { this.editor.dispose(); const model = this.editor.getModel(); if (model) { model.dispose(); } } if (this._subscription) { this._subscription.dispose(); } } extract(code: string, keyWord: string): string[] { // TODO: add different processors for contract, scripts and transactions const target = code .split(/\r\n|\n|\r/) .find((line) => line.includes(keyWord)); if (target) { const match = target.match(/(?:\()(.*)(?:\))/); if (match) { return match[1].split(',').map((item) => item.replace(/\s*/g, '')); } } return []; } extractSigners(code: string): number { return this.extract(code, 'prepare').filter((item) => !!item).length; } hover(highlight: Highlight): void { const { startLine, startColumn, endLine, endColumn, color } = highlight; const model = this.editor.getModel(); const selection = model.getAllDecorations().find((item: any) => { return ( item.range.startLineNumber === startLine && item.range.startColumn === startColumn ); }); const selectionEndLine = selection ? selection.range.endLineNumber : endLine; const selectionEndColumn = selection ? selection.range.endColumn : endColumn; const highlightLine = [ { range: new monaco.Range(startLine, startColumn, endLine, endColumn), options: { isWholeLine: true, className: `playground-syntax-${color}-hover`, }, }, { range: new monaco.Range( startLine, startColumn, selectionEndLine, selectionEndColumn, ), options: { isWholeLine: false, className: `playground-syntax-${color}-hover-selection`, }, }, ]; this.editor.getModel().deltaDecorations([], highlightLine); this.editor.revealLineInCenter(startLine); } hideDecorations(): void { const model = this.editor.getModel(); let current = model .getAllDecorations() .filter((item) => { const { className } = item.options; return className?.includes('playground-syntax'); }) .map((item) => item.id); model.deltaDecorations(current, []); } render() { const { type, code } = this.props; /// Get a list of args from language server const { activeId } = this.props; const { args, problems } = this.state; const list = args[activeId] || []; /// Extract number of signers from code const signers = this.extractSigners(code); const problemsList: ProblemsList = problems[activeId] || { error: [], warning: [], hint: [], info: [], }; return ( <EditorContainer id={this.props.mount}> <Arguments type={type} list={list} signers={signers} problems={problemsList} hover={(highlight) => this.hover(highlight)} hideDecorations={() => this.hideDecorations()} goTo={(position: monaco.IPosition) => goTo(this.editor, position)} editor={this.editor} languageClient={this.languageClient} /> </EditorContainer> ); } } export default CadenceEditor;
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component"; import {Model, AnyTrait, TraitFactory, Trait} from "@swim/model"; import {AnyView, ViewFactory, View} from "@swim/view"; /** @internal */ export type TraitViewRefTraitType<F extends TraitViewRef<any, any, any>> = F extends TraitViewRef<any, infer T, any> ? T : never; /** @internal */ export type TraitViewRefViewType<F extends TraitViewRef<any, any, any>> = F extends TraitViewRef<any, any, infer V> ? V : never; /** @public */ export interface TraitViewRefInit<T extends Trait = Trait, V extends View = View> extends FastenerInit { extends?: {prototype: TraitViewRef<any, any, any>} | string | boolean | null; traitKey?: string | boolean; traitType?: TraitFactory<T>; bindsTrait?: boolean; observesTrait?: boolean; initTrait?(trait: T): void; willAttachTrait?(trait: T, target: Trait | null): void; didAttachTrait?(trait: T, target: Trait | null): void; deinitTrait?(trait: T): void; willDetachTrait?(trait: T): void; didDetachTrait?(trait: T): void; parentModel?: Model | null; insertChildTrait?(model: Model, trait: T, target: Trait | null, key: string | undefined): void; detectTrait?(trait: Trait): T | null; createTrait?(): T; fromAnyTrait?(value: AnyTrait<T>): T; viewKey?: string | boolean; viewType?: ViewFactory<V>; bindsView?: boolean; observesView?: boolean; initView?(view: V): void; willAttachView?(view: V, target: View | null): void; didAttachView?(view: V, target: View | null): void; deinitView?(view: V): void; willDetachView?(view: V): void; didDetachView?(view: V): void; parentView?: View | null; insertChildView?(parent: View, child: V, target: View | null, key: string | undefined): void; detectView?(view: View): V | null; createView?(): V; fromAnyView?(value: AnyView<V>): V; } /** @public */ export type TraitViewRefDescriptor<O = unknown, T extends Trait = Trait, V extends View = View, I = {}> = ThisType<TraitViewRef<O, T, V> & I> & TraitViewRefInit<T, V> & Partial<I>; /** @public */ export interface TraitViewRefClass<F extends TraitViewRef<any, any, any> = TraitViewRef<any, any, any>> extends FastenerClass<F> { } /** @public */ export interface TraitViewRefFactory<F extends TraitViewRef<any, any, any> = TraitViewRef<any, any, any>> extends TraitViewRefClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitViewRefFactory<F> & I; define<O, T extends Trait = Trait, V extends View = View>(className: string, descriptor: TraitViewRefDescriptor<O, T, V>): TraitViewRefFactory<TraitViewRef<any, T, V>>; define<O, T extends Trait = Trait, V extends View = View>(className: string, descriptor: {observesTrait: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<T>>): TraitViewRefFactory<TraitViewRef<any, T, V>>; define<O, T extends Trait = Trait, V extends View = View>(className: string, descriptor: {observesView: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<V>>): TraitViewRefFactory<TraitViewRef<any, T, V>>; define<O, T extends Trait = Trait, V extends View = View>(className: string, descriptor: {observesTrait: boolean, observesView: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<T> & ObserverType<V>>): TraitViewRefFactory<TraitViewRef<any, T, V>>; define<O, T extends Trait = Trait, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & TraitViewRefDescriptor<O, T, V, I>): TraitViewRefFactory<TraitViewRef<any, T, V> & I>; define<O, T extends Trait = Trait, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observesTrait: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<T>>): TraitViewRefFactory<TraitViewRef<any, T, V> & I>; define<O, T extends Trait = Trait, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observesView: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<V>>): TraitViewRefFactory<TraitViewRef<any, T, V> & I>; define<O, T extends Trait = Trait, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observesTrait: boolean, observesView: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<T> & ObserverType<V>>): TraitViewRefFactory<TraitViewRef<any, T, V> & I>; <O, T extends Trait = Trait, V extends View = View>(descriptor: TraitViewRefDescriptor<O, T, V>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View>(descriptor: {observesTrait: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<T>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View>(descriptor: {observesView: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<V>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View>(descriptor: {observesTrait: boolean, observesView: boolean} & TraitViewRefDescriptor<O, T, V, ObserverType<T> & ObserverType<V>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, I = {}>(descriptor: {implements: unknown} & TraitViewRefDescriptor<O, T, V, I>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, I = {}>(descriptor: {implements: unknown; observesTrait: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<T>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, I = {}>(descriptor: {implements: unknown; observesView: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<V>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, I = {}>(descriptor: {implements: unknown; observesTrait: boolean, observesView: boolean} & TraitViewRefDescriptor<O, T, V, I & ObserverType<T> & ObserverType<V>>): PropertyDecorator; } /** @public */ export interface TraitViewRef<O = unknown, T extends Trait = Trait, V extends View = View> extends Fastener<O> { /** @override */ get fastenerType(): Proto<TraitViewRef<any, any, any>>; /** @protected @override */ onInherit(superFastener: Fastener): void; readonly trait: T | null; getTrait(): T; setTrait(trait: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null; attachTrait<T2 extends T>(trait: T2 | TraitFactory<T2>, target?: Trait | null): T2; attachTrait(trait: AnyTrait<T>, target?: Trait | null): T; attachTrait(trait?: AnyTrait<T> | null, target?: Trait | null): T | null; detachTrait(): T | null; /** @protected */ initTrait(trait: T): void; /** @protected */ willAttachTrait(trait: T, target: Trait | null): void; /** @protected */ onAttachTrait(trait: T, target: Trait | null): void; /** @protected */ didAttachTrait(trait: T, target: Trait | null): void; /** @protected */ deinitTrait(trait: T): void; /** @protected */ willDetachTrait(trait: T): void; /** @protected */ onDetachTrait(trait: T): void; /** @protected */ didDetachTrait(trait: T): void; insertTrait(model?: Model | null, trait?: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null; removeTrait(): T | null; deleteTrait(): T | null; /** @internal @protected */ get parentModel(): Model | null; /** @internal @protected */ insertChildTrait(model: Model, trait: T, target: Trait | null, key: string | undefined): void; /** @internal @override */ bindModel(model: Model, targetModel: Model | null): void; /** @internal @override */ unbindModel(model: Model): void; /** @override */ detectModel(model: Model): T | null; /** @internal */ bindTrait(trait: Trait, target: Trait | null): void; /** @internal */ unbindTrait(trait: Trait): void; detectTrait(trait: Trait): T | null; createTrait(): T; /** @internal @protected */ fromAnyTrait(value: AnyTrait<T>): T; /** @internal */ get traitKey(): string | undefined; // optional prototype field /** @internal @protected */ get traitType(): TraitFactory<T> | undefined; // optional prototype property /** @internal @protected */ get bindsTrait(): boolean | undefined; // optional prototype property /** @internal @protected */ get observesTrait(): boolean | undefined; // optional prototype property readonly view: V | null; getView(): V; setView(view: AnyView<V> | null, target?: View | null, key?: string): V | null; attachView<V2 extends V>(view: V2 | ViewFactory<V2>, target?: View | null): V2; attachView(view: AnyView<V>, target?: View | null): V; attachView(view?: AnyView<V> | null, target?: View | null): V | null; detachView(): V | null; /** @protected */ initView(view: V): void; /** @protected */ willAttachView(view: V, target: View | null): void; /** @protected */ onAttachView(view: V, target: View | null): void; /** @protected */ didAttachView(view: V, target: View | null): void; /** @protected */ deinitView(view: V): void; /** @protected */ willDetachView(view: V): void; /** @protected */ onDetachView(view: V): void; /** @protected */ didDetachView(view: V): void; insertView(parent?: View | null, view?: AnyView<V> | null, target?: View | null, key?: string): V | null; removeView(): V | null; deleteView(): V | null; /** @internal @protected */ get parentView(): View | null; /** @internal @protected */ insertChildView(parent: View, child: V, target: View | null, key: string | undefined): void; /** @internal */ bindView(view: View, target: View | null): void; /** @internal */ unbindView(view: View): void; detectView(view: View): V | null; createView(): V; /** @internal @protected */ fromAnyView(value: AnyView<V>): V; /** @internal */ get viewKey(): string | undefined; // optional prototype field /** @internal @protected */ get viewType(): ViewFactory<V> | undefined; // optional prototype property /** @internal @protected */ get bindsView(): boolean | undefined; // optional prototype property /** @internal @protected */ get observesView(): boolean | undefined; // optional prototype property /** @internal @override */ get lazy(): boolean; // prototype property /** @internal @override */ get static(): string | boolean; // prototype property } /** @public */ export const TraitViewRef = (function (_super: typeof Fastener) { const TraitViewRef: TraitViewRefFactory = _super.extend("TraitViewRef"); Object.defineProperty(TraitViewRef.prototype, "fastenerType", { get: function (this: TraitViewRef): Proto<TraitViewRef<any, any, any>> { return TraitViewRef; }, configurable: true, }); TraitViewRef.prototype.onInherit = function (this: TraitViewRef, superFastener: TraitViewRef): void { this.setTrait(superFastener.trait); this.setView(superFastener.view); }; TraitViewRef.prototype.getTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>): T { const trait = this.trait; if (trait === null) { let message = trait + " "; if (this.name.length !== 0) { message += this.name + " "; } message += "trait"; throw new TypeError(message); } return trait; }; TraitViewRef.prototype.setTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, newTrait: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null { if (newTrait !== null) { newTrait = this.fromAnyTrait(newTrait); } let oldTrait = this.trait; if (oldTrait !== newTrait) { if (target === void 0) { target = null; } let model: Model | null; if (this.bindsTrait && (model = this.parentModel, model !== null)) { if (oldTrait !== null && oldTrait.model === model) { if (target === null) { target = oldTrait.nextTrait; } oldTrait.remove(); } if (newTrait !== null) { if (key === void 0) { key = this.traitKey; } this.insertChildTrait(model, newTrait, target, key); } oldTrait = this.trait; } if (oldTrait !== newTrait) { if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } if (newTrait !== null) { this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } } } return oldTrait; }; TraitViewRef.prototype.attachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, newTrait?: AnyTrait<T> | null, target?: Trait | null): T | null { const oldTrait = this.trait; if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAnyTrait(newTrait); } else if (oldTrait === null) { newTrait = this.createTrait(); } else { newTrait = oldTrait; } if (newTrait !== oldTrait) { if (target === void 0) { target = null; } if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitViewRef.prototype.detachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>): T | null { const oldTrait = this.trait; if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } return oldTrait; }; TraitViewRef.prototype.initTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T): void { // hook }; TraitViewRef.prototype.willAttachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T, target: Trait | null): void { // hook }; TraitViewRef.prototype.onAttachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T, target: Trait | null): void { if (this.observesTrait === true) { trait.observe(this as ObserverType<T>); } }; TraitViewRef.prototype.didAttachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T, target: Trait | null): void { // hook }; TraitViewRef.prototype.deinitTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T): void { // hook }; TraitViewRef.prototype.willDetachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T): void { // hook }; TraitViewRef.prototype.onDetachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T): void { if (this.observesTrait === true) { trait.unobserve(this as ObserverType<T>); } }; TraitViewRef.prototype.didDetachTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: T): void { // hook }; TraitViewRef.prototype.insertTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, model?: Model | null, newTrait?: AnyTrait<T> | null, target?: Trait | null, key?: string): T | null { if (newTrait !== void 0 && newTrait !== null) { newTrait = this.fromAnyTrait(newTrait); } else { const oldTrait = this.trait; if (oldTrait === null) { newTrait = this.createTrait(); } else { newTrait = oldTrait; } } if (model === void 0 || model === null) { model = this.parentModel; } if (target === void 0) { target = null; } if (key === void 0) { key = this.traitKey; } if (model !== null && (newTrait.parent !== model || newTrait.key !== key)) { this.insertChildTrait(model, newTrait, target, key); } const oldTrait = this.trait; if (newTrait !== oldTrait) { if (oldTrait !== null) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); oldTrait.remove(); } this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } return newTrait; }; TraitViewRef.prototype.removeTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>): T | null { const trait = this.trait; if (trait !== null) { trait.remove(); } return trait; }; TraitViewRef.prototype.deleteTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>): T | null { const trait = this.detachTrait(); if (trait !== null) { trait.remove(); } return trait; }; Object.defineProperty(TraitViewRef.prototype, "parentModel", { get(this: TraitViewRef): Model | null { const owner = this.owner; if (owner instanceof Model) { return owner; } else if (owner instanceof Trait) { return owner.model; } else { return null; } }, configurable: true, }); TraitViewRef.prototype.insertChildTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, model: Model, trait: T, target: Trait | null, key: string | undefined): void { model.insertTrait(trait, target, key); }; TraitViewRef.prototype.bindModel = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, model: Model, targetModel: Model | null): void { if (this.bindsTrait && this.trait === null) { const newTrait = this.detectModel(model); if (newTrait !== null) { this.willAttachTrait(newTrait, null); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, null); this.initTrait(newTrait); this.didAttachTrait(newTrait, null); } } }; TraitViewRef.prototype.unbindModel = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, model: Model): void { if (this.bindsTrait) { const oldTrait = this.detectModel(model); if (oldTrait !== null && this.trait === oldTrait) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitViewRef.prototype.detectModel = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, model: Model): T | null { return null; }; TraitViewRef.prototype.bindTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: Trait, target: Trait | null): void { if (this.bindsTrait && this.trait === null) { const newTrait = this.detectTrait(trait); if (newTrait !== null) { this.willAttachTrait(newTrait, target); (this as Mutable<typeof this>).trait = newTrait; this.onAttachTrait(newTrait, target); this.initTrait(newTrait); this.didAttachTrait(newTrait, target); } } }; TraitViewRef.prototype.unbindTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: Trait): void { if (this.bindsTrait) { const oldTrait = this.detectTrait(trait); if (oldTrait !== null && this.trait === oldTrait) { this.willDetachTrait(oldTrait); (this as Mutable<typeof this>).trait = null; this.onDetachTrait(oldTrait); this.deinitTrait(oldTrait); this.didDetachTrait(oldTrait); } } }; TraitViewRef.prototype.detectTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, trait: Trait): T | null { const key = this.traitKey; if (key !== void 0 && key === trait.key) { return trait as T; } return null; }; TraitViewRef.prototype.createTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>): T { let trait: T | undefined; const type = this.traitType; if (type !== void 0) { trait = type.create(); } if (trait === void 0 || trait === null) { let message = "Unable to create "; if (this.name.length !== 0) { message += this.name + " "; } message += "trait"; throw new Error(message); } return trait; }; TraitViewRef.prototype.fromAnyTrait = function <T extends Trait>(this: TraitViewRef<unknown, T, View>, value: AnyTrait<T>): T { const type = this.traitType; if (type !== void 0) { return type.fromAny(value); } else { return Trait.fromAny(value) as T; } }; TraitViewRef.prototype.getView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>): V { const view = this.view; if (view === null) { let message = view + " "; if (this.name.length !== 0) { message += this.name + " "; } message += "view"; throw new TypeError(message); } return view; }; TraitViewRef.prototype.setView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, newView: AnyView<V> | null, target?: View | null, key?: string): V | null { if (newView !== null) { newView = this.fromAnyView(newView); } let oldView = this.view; if (oldView !== newView) { if (target === void 0) { target = null; } let parent: View | null; if (this.bindsView && (parent = this.parentView, parent !== null)) { if (oldView !== null && oldView.parent === parent) { if (target === null) { target = oldView.nextSibling; } oldView.remove(); } if (newView !== null) { if (key === void 0) { key = this.viewKey; } this.insertChildView(parent, newView, target, key); } oldView = this.view; } if (oldView !== newView) { if (oldView !== null) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); } if (newView !== null) { this.willAttachView(newView, target); (this as Mutable<typeof this>).view = newView; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } } } return oldView; }; TraitViewRef.prototype.attachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, newView?: AnyView<V> | null, target?: View | null): V | null { const oldView = this.view; if (newView !== void 0 && newView !== null) { newView = this.fromAnyView(newView); } else if (oldView === null) { newView = this.createView(); } else { newView = oldView; } if (newView !== oldView) { if (target === void 0) { target = null; } if (oldView !== null) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); } this.willAttachView(newView, target); (this as Mutable<typeof this>).view = newView; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } return newView; }; TraitViewRef.prototype.detachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>): V | null { const oldView = this.view; if (oldView !== null) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); } return oldView; }; TraitViewRef.prototype.initView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V): void { // hook }; TraitViewRef.prototype.willAttachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V, target: View | null): void { // hook }; TraitViewRef.prototype.onAttachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V, target: View | null): void { if (this.observesView === true) { view.observe(this as ObserverType<V>); } }; TraitViewRef.prototype.didAttachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V, target: View | null): void { // hook }; TraitViewRef.prototype.deinitView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V): void { // hook }; TraitViewRef.prototype.willDetachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V): void { // hook }; TraitViewRef.prototype.onDetachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V): void { if (this.observesView === true) { view.unobserve(this as ObserverType<V>); } }; TraitViewRef.prototype.didDetachView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: V): void { // hook }; TraitViewRef.prototype.insertView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, parent?: View | null, newView?: AnyView<V> | null, target?: View | null, key?: string): V | null { if (newView !== void 0 && newView !== null) { newView = this.fromAnyView(newView); } else { const oldView = this.view; if (oldView === null) { newView = this.createView(); } else { newView = oldView; } } if (parent === void 0 || parent === null) { parent = this.parentView; } if (target === void 0) { target = null; } if (key === void 0) { key = this.viewKey; } if (parent !== null && (newView.parent !== parent || newView.key !== key)) { this.insertChildView(parent, newView, target, key); } const oldView = this.view; if (newView !== oldView) { if (oldView !== null) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); oldView.remove(); } this.willAttachView(newView, target); (this as Mutable<typeof this>).view = newView; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } return newView; }; TraitViewRef.prototype.removeView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>): V | null { const view = this.view; if (view !== null) { view.remove(); } return view; }; TraitViewRef.prototype.deleteView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>): V | null { const view = this.detachView(); if (view !== null) { view.remove(); } return view; }; Object.defineProperty(TraitViewRef.prototype, "parentView", { get(this: TraitViewRef): View | null { const owner = this.owner; return owner instanceof View ? owner : null; }, configurable: true, }); TraitViewRef.prototype.insertChildView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, parent: View, child: V, target: View | null, key: string | undefined): void { parent.insertChild(child, target, key); }; TraitViewRef.prototype.bindView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: View, target: View | null): void { if (this.bindsView && this.view === null) { const newView = this.detectView(view); if (newView !== null) { this.willAttachView(newView, target); (this as Mutable<typeof this>).view = newView; this.onAttachView(newView, target); this.initView(newView); this.didAttachView(newView, target); } } }; TraitViewRef.prototype.unbindView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: View): void { if (this.bindsView) { const oldView = this.detectView(view); if (oldView !== null && this.view === oldView) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.deinitView(oldView); this.didDetachView(oldView); } } }; TraitViewRef.prototype.detectView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, view: View): V | null { const key = this.viewKey; if (key !== void 0 && key === view.key) { return view as V; } return null; }; TraitViewRef.prototype.createView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>): V { let view: V | undefined; const type = this.viewType; if (type !== void 0) { view = type.create(); } if (view === void 0 || view === null) { let message = "Unable to create "; if (this.name.length !== 0) { message += this.name + " "; } message += "view"; throw new Error(message); } return view; }; TraitViewRef.prototype.fromAnyView = function <V extends View>(this: TraitViewRef<unknown, Trait, V>, value: AnyView<V>): V { const type = this.viewType; if (type !== void 0) { return type.fromAny(value); } else { return View.fromAny(value) as V; } }; Object.defineProperty(TraitViewRef.prototype, "lazy", { get: function (this: TraitViewRef): boolean { return false; }, configurable: true, }); Object.defineProperty(TraitViewRef.prototype, "static", { get: function (this: TraitViewRef): string | boolean { return true; }, configurable: true, }); TraitViewRef.construct = function <F extends TraitViewRef<any, any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).trait = null; (fastener as Mutable<typeof fastener>).view = null; return fastener; }; TraitViewRef.define = function <O, T extends Trait, V extends View>(className: string, descriptor: TraitViewRefDescriptor<O, T, V>): TraitViewRefFactory<TraitViewRef<any, T, V>> { let superClass = descriptor.extends as TraitViewRefFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; if (descriptor.traitKey === true) { Object.defineProperty(descriptor, "traitKey", { value: className, configurable: true, }); } else if (descriptor.traitKey === false) { Object.defineProperty(descriptor, "traitKey", { value: void 0, configurable: true, }); } if (descriptor.viewKey === true) { Object.defineProperty(descriptor, "viewKey", { value: className, configurable: true, }); } else if (descriptor.viewKey === false) { Object.defineProperty(descriptor, "viewKey", { value: void 0, configurable: true, }); } if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: TraitViewRef<any, any, any>}, fastener: TraitViewRef<O, T, V> | null, owner: O): TraitViewRef<O, T, V> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } return fastener; }; return fastenerClass; }; return TraitViewRef; })(Fastener);
the_stack
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { IThemeManager } from '@jupyterlab/apputils'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; const extensionId = 'jupyterlab-tailwind-theme:plugin'; /** * A plugin for jupyterlab-tailwind-theme * Since the JupyterLab theme extension seem to only allow for one index.css file, there is a set of variables * defined in index.css which is overridden here depending of the choice of theme. */ const plugin: JupyterFrontEndPlugin<void> = { id: extensionId, requires: [IThemeManager, ISettingRegistry], activate: function(app: JupyterFrontEnd, manager: IThemeManager, settingRegistry: ISettingRegistry,) { const style = 'jupyterlab-tailwind-theme/index.css'; let width = ""; // Load settings Promise.all([ settingRegistry.load(extensionId), app.restored ]).then(async ([settings]) => { width = settings.get('maxCellWidth').composite.toString(); document.documentElement.style.setProperty('--max-cell-width', width); }); manager.register({ name: 'Tailwind Light', isLight: true, load: () => { // Theme colors document.documentElement.style.setProperty('--tailwind-layout-color0', 'rgb(var(--tailwind-white))'); document.documentElement.style.setProperty('--tailwind-layout-color1', 'rgb(var(--tailwind-white))'); document.documentElement.style.setProperty('--tailwind-layout-color2', 'var(--tailwind-grey-300)'); document.documentElement.style.setProperty('--tailwind-layout-color3', 'var(--tailwind-indigo-600)'); document.documentElement.style.setProperty('--tailwind-layout-color4', 'var(--tailwind-grey-600)'); document.documentElement.style.setProperty('--tailwind-inverse-layout-color2', 'var(--tailwind-grey-400)'); document.documentElement.style.setProperty('--tailwind-inverse-layout-color3', 'var(--tailwind-indigo-800)'); // Object & font colors document.documentElement.style.setProperty('--tailwind-background-color', 'var(--tailwind-grey-100)'); document.documentElement.style.setProperty('--tailwind-code-cell-color', 'var(--md-grey-100)'); document.documentElement.style.setProperty('--tailwind-base-font-color', 'var(--tailwind-black)'); document.documentElement.style.setProperty('--tailwind-inverse-font-color', 'var(--tailwind-white)'); document.documentElement.style.setProperty('--jp-rendermime-error-background', 'var(--tailwind-red-200)'); // Menu color document.documentElement.style.setProperty('--tailwind-menu-color', 'var(--tailwind-indigo-800)'); // Line border color document.documentElement.style.setProperty('--jp-border-color2', 'var(--tailwind-grey-400)'); // Editor colors document.documentElement.style.setProperty('--jp-mirror-editor-keyword-color', 'var(--tailwind-green-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-atom-color', 'var(--tailwind-blue-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-number-color', '#080'); document.documentElement.style.setProperty('--jp-mirror-editor-def-color', '#00f'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-color', 'var(--jp-content-font-color1)'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-2-color', 'var(--tailwind-blue-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-3-color', 'var(--tailwind-green-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-punctuation-color', 'var(--tailwind-blue-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-property-color', 'var(--tailwind-blue-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-operator-color', '#aa22ff'); document.documentElement.style.setProperty('--jp-mirror-editor-comment-color', '#408080'); document.documentElement.style.setProperty('--jp-mirror-editor-string-color', '#ba2121'); document.documentElement.style.setProperty('--jp-mirror-editor-string-2-color', '#708'); document.documentElement.style.setProperty('--jp-mirror-editor-meta-color', '#aa22ff'); document.documentElement.style.setProperty('--jp-mirror-editor-qualifier-color', '#555'); document.documentElement.style.setProperty('--jp-mirror-editor-builtin-color', 'var(--tailwind-green-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-bracket-color', '#997'); document.documentElement.style.setProperty('--jp-mirror-editor-tag-color', 'var(--tailwind-green-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-attribute-color', 'var(--tailwind-blue-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-header-color', 'var(--tailwind-blue-500)'); document.documentElement.style.setProperty('--jp-mirror-editor-quote-color', 'var(--tailwind-green-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-link-color', 'var(--tailwind-blue-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-error-color', '#f00'); document.documentElement.style.setProperty('--jp-mirror-editor-hr-color', '#999'); document.documentElement.style.setProperty('--jp-notebook-multiselected-color', 'var(--tailwind-blue-100)'); // Search result highlighting document.documentElement.style.setProperty('--jp-search-selected-match-background-color', 'var(--tailwind-green-400)'); document.documentElement.style.setProperty('--jp-search-unselected-match-background-color', 'var(--tailwind-green-200)'); // Scrollbar color document.documentElement.style.setProperty('--tailwind-scrollbar-thumb-color', 'var(--tailwind-grey-400)'); return manager.loadCSS(style) }, unload: () => Promise.resolve(undefined) }); manager.register({ name: 'Tailwind Dark', isLight: false, load: () => { // Theme colors document.documentElement.style.setProperty('--tailwind-layout-color0', 'var(--tailwind-grey-900)'); document.documentElement.style.setProperty('--tailwind-layout-color1', 'var(--tailwind-grey-900)'); document.documentElement.style.setProperty('--tailwind-layout-color2', 'var(--tailwind-grey-950)'); document.documentElement.style.setProperty('--tailwind-layout-color3', 'var(--tailwind-indigo-300)'); document.documentElement.style.setProperty('--tailwind-layout-color4', 'var(--tailwind-grey-400)'); document.documentElement.style.setProperty('--tailwind-inverse-layout-color2', 'var(--tailwind-grey-600)'); document.documentElement.style.setProperty('--tailwind-inverse-layout-color3', 'var(--tailwind-indigo-600)'); // Object & font colors document.documentElement.style.setProperty('--tailwind-background-color', 'rgb(var(--tailwind-black))'); document.documentElement.style.setProperty('--tailwind-code-cell-color', 'var(--tailwind-grey-800)'); document.documentElement.style.setProperty('--tailwind-base-font-color', 'var(--tailwind-white)'); document.documentElement.style.setProperty('--tailwind-inverse-font-color', 'var(--tailwind-black)'); document.documentElement.style.setProperty('--jp-rendermime-error-background', 'var(--tailwind-red-900)'); // Menu color document.documentElement.style.setProperty('--tailwind-menu-color', 'var(--tailwind-indigo-800)'); // Line border color document.documentElement.style.setProperty('--jp-border-color2', 'var(--tailwind-grey-700)'); // Editor colors document.documentElement.style.setProperty('--jp-mirror-editor-keyword-color', 'var(--tailwind-green-500)'); document.documentElement.style.setProperty('--jp-mirror-editor-atom-color', 'var(--tailwind-blue-300)'); document.documentElement.style.setProperty('--jp-mirror-editor-number-color', '#b5cea8'); document.documentElement.style.setProperty('--jp-mirror-editor-def-color', '#79d9ff'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-color', 'var(--jp-content-font-color1)'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-2-color', '#79d9ff'); document.documentElement.style.setProperty('--jp-mirror-editor-variable-3-color', 'var(--tailwind-green-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-punctuation-color', '#79d9ff'); document.documentElement.style.setProperty('--jp-mirror-editor-property-color', '#79d9ff'); document.documentElement.style.setProperty('--jp-mirror-editor-operator-color', '#daabf7'); document.documentElement.style.setProperty('--jp-mirror-editor-comment-color', '#aebca8'); document.documentElement.style.setProperty('--jp-mirror-editor-string-color', '#ce9178'); document.documentElement.style.setProperty('--jp-mirror-editor-string-2-color', 'var(--tailwind-purple-300)'); document.documentElement.style.setProperty('--jp-mirror-editor-meta-color', '#daabf7'); document.documentElement.style.setProperty('--jp-mirror-editor-qualifier-color', '#555'); document.documentElement.style.setProperty('--jp-mirror-editor-builtin-color', 'var(--tailwind-green-600)'); document.documentElement.style.setProperty('--jp-mirror-editor-bracket-color', '#997'); document.documentElement.style.setProperty('--jp-mirror-editor-tag-color', 'var(--tailwind-green-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-attribute-color', 'var(--tailwind-blue-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-header-color', 'var(--tailwind-blue-500)'); document.documentElement.style.setProperty('--jp-mirror-editor-quote-color', 'var(--tailwind-green-300)'); document.documentElement.style.setProperty('--jp-mirror-editor-link-color', 'var(--tailwind-blue-700)'); document.documentElement.style.setProperty('--jp-mirror-editor-error-color', '#f00'); document.documentElement.style.setProperty('--jp-mirror-editor-hr-color', '#999'); document.documentElement.style.setProperty('--jp-notebook-multiselected-color', 'var(--tailwind-blue-900)'); // Search result highlighting document.documentElement.style.setProperty('--jp-search-selected-match-background-color', 'var(--tailwind-green-600)'); document.documentElement.style.setProperty('--jp-search-unselected-match-background-color', 'var(--tailwind-green-800)'); // Scrollbar color document.documentElement.style.setProperty('--tailwind-scrollbar-thumb-color', 'var(--tailwind-grey-700)'); return manager.loadCSS(style) }, unload: () => Promise.resolve(undefined) }); }, autoStart: true }; export default plugin;
the_stack
import * as vscode from "vscode"; import * as fs from "fs"; import * as path from "path"; import parseXML = require("@rgrove/parse-xml"); import validateFrameworkSDK from "../utils/validateFrameworkSDK"; const FILE_EXTENSION_AS3PROJ = ".as3proj"; const FILE_ASCONFIG_JSON = "asconfig.json"; const FILE_APPLICATION_XML = "application.xml"; const MESSAGE_IMPORT_START = "🚀 Importing FlashDevelop project..."; const MESSAGE_IMPORT_COMPLETE = "✅ Import complete."; const MESSAGE_IMPORT_FAILED = "❌ Import failed."; const ERROR_NO_FOLDER = "Workspace folder parameter is missing."; const ERROR_NO_PROJECTS = "No FlashDevelop projects found in workspace."; const ERROR_FILE_READ = "Failed to read file: "; const ERROR_XML_PARSE = "Failed to parse FlashDevelop project. Invalid XML in file: "; const ERROR_PROJECT_PARSE = "Failed to parse FlashDevelop project: "; const WARNING_INVALID_DEFINE = "Failed to parse define: "; const WARNING_PRE_BUILD_COMMAND = "Custom pre-build commands are not supported. Skipping... "; const WARNING_POST_BUILD_COMMAND = "Custom post-build commands are not supported. Skipping... "; const WARNING_TEST_MOVIE_COMMAND = "Custom test movie commands are not supported. Skipping... "; const WARNING_COMMAND_TASK = 'To run this command, you may define a custom "shell" task in .vscode/tasks.json.'; const WARNING_RSL_PATHS = "Runtime shared libraries are not supported. Skipping... "; const WARNING_LIBRARY_ASSETS = "Library assets are not supported. Skipping... "; const CHANNEL_NAME_IMPORTER = "FlashDevelop Importer"; export function isFlashDevelopProject(folder: vscode.WorkspaceFolder) { let idealProjectPath = path.resolve( folder.uri.fsPath, folder.name + FILE_EXTENSION_AS3PROJ ); if (fs.existsSync(idealProjectPath)) { return true; } return fs.readdirSync(folder.uri.fsPath).some((file) => { return path.extname(file) === FILE_EXTENSION_AS3PROJ; }); } function findProjectFile(folder: vscode.WorkspaceFolder) { let idealProjectPath = path.resolve( folder.uri.fsPath, folder.name + FILE_EXTENSION_AS3PROJ ); if (fs.existsSync(idealProjectPath)) { return idealProjectPath; } let fileName = fs.readdirSync(folder.uri.fsPath).find((file) => { return path.extname(file) === FILE_EXTENSION_AS3PROJ; }); if (fileName === undefined) { return null; } return path.resolve(folder.uri.fsPath, fileName); } export function importFlashDevelopProject( workspaceFolder: vscode.WorkspaceFolder ) { getOutputChannel().clear(); getOutputChannel().appendLine(MESSAGE_IMPORT_START); getOutputChannel().show(true); let result = importFlashDevelopProjectInternal(workspaceFolder); if (result) { getOutputChannel().appendLine(MESSAGE_IMPORT_COMPLETE); } else { getOutputChannel().appendLine(MESSAGE_IMPORT_FAILED); } } function importFlashDevelopProjectInternal( workspaceFolder: vscode.WorkspaceFolder ) { if (!workspaceFolder) { addError(ERROR_NO_FOLDER); return false; } let projectFilePath = findProjectFile(workspaceFolder); if (!projectFilePath) { addError(ERROR_NO_PROJECTS); return false; } let projectText = null; try { projectText = fs.readFileSync(projectFilePath, "utf8"); } catch (error) { addError(ERROR_FILE_READ + projectFilePath); return false; } let project = null; try { let parsedXML = parseXML(projectText); project = parsedXML.children[0]; } catch (error) { addError(ERROR_XML_PARSE + projectFilePath); return false; } try { let result = createProjectFiles( workspaceFolder.uri.fsPath, projectFilePath, project ); if (!result) { return false; } } catch (error) { addError(ERROR_PROJECT_PARSE + projectFilePath); if (error instanceof Error) { getOutputChannel().appendLine(error.stack); } return false; } return true; } function createProjectFiles( folderPath: string, projectFilePath: string, project: any ) { let result: any = { compilerOptions: {}, }; migrateProjectFile(project, result); let appName = path.basename(projectFilePath); let fileName = FILE_ASCONFIG_JSON; let asconfigPath = path.resolve(folderPath, fileName); let resultText = JSON.stringify(result, undefined, "\t"); fs.writeFileSync(asconfigPath, resultText); vscode.workspace.openTextDocument(asconfigPath).then((document) => { vscode.window.showTextDocument(document); }); getOutputChannel().appendLine(appName + " ➡ " + fileName); return true; } function migrateProjectFile(project: any, result: any) { let rootChildren = project.children as any[]; if (!rootChildren) { return null; } let classpathsElement = findChildElementByName(rootChildren, "classpaths"); if (classpathsElement) { migrateClasspathsElement(classpathsElement, result); } let compileTargetsElement = findChildElementByName( rootChildren, "compileTargets" ); if (compileTargetsElement) { migrateCompileTargetsElement(compileTargetsElement, result); } let outputElement = findChildElementByName(rootChildren, "output"); if (outputElement) { migrateOutputElement(outputElement, result); } let buildElement = findChildElementByName(rootChildren, "build"); if (buildElement) { migrateBuildElement(buildElement, result); } let libraryPathsElement = findChildElementByName( rootChildren, "libraryPaths" ); if (libraryPathsElement) { migrateLibraryPathsElement(libraryPathsElement, result); } let externalLibraryPathsElement = findChildElementByName( rootChildren, "externalLibraryPaths" ); if (externalLibraryPathsElement) { migrateExternalLibraryPathsElement(externalLibraryPathsElement, result); } let includeLibrariesElement = findChildElementByName( rootChildren, "includeLibraries" ); if (includeLibrariesElement) { migrateIncludeLibrariesElement(includeLibrariesElement, result); } let rslPathsElement = findChildElementByName(rootChildren, "rslPaths"); if (rslPathsElement) { migrateRslPathsElement(rslPathsElement, result); } let preBuildCommandElement = findChildElementByName( rootChildren, "preBuildCommand" ); if (preBuildCommandElement) { migratePreBuildCommandElement(preBuildCommandElement, result); } let postBuildCommandElement = findChildElementByName( rootChildren, "postBuildCommand" ); if (postBuildCommandElement) { migratePostBuildCommandElement(postBuildCommandElement, result); } let optionsElement = findChildElementByName(rootChildren, "options"); if (optionsElement) { migrateOptionsElement(optionsElement, result); } let libraryElement = findChildElementByName(rootChildren, "library"); if (libraryElement) { migrateLibraryElement(libraryElement, result); } } function migrateClasspathsElement(classpathsElement: any, result: any) { let sourcePaths = []; let children = classpathsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "class") { return; } let attributes = child.attributes; if ("path" in attributes) { let sourcePath = attributes.path as string; sourcePath = normalizeFilePath(sourcePath); if (sourcePath.length > 0) { sourcePaths.push(sourcePath); } } }); if (sourcePaths.length > 0) { result.compilerOptions["source-path"] = sourcePaths; } } function migrateCompileTargetsElement(compileTargetsElement: any, result: any) { let files = []; let children = compileTargetsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "compile") { return; } let attributes = child.attributes; if ("path" in attributes) { let compileTargetPath = attributes.path as string; compileTargetPath = normalizeFilePath(compileTargetPath); if (compileTargetPath.length > 0) { files.push(compileTargetPath); } } }); if (files.length > 0) { result.files = files; } } function migrateOutputElement(outputElement: any, result: any) { let width = 800; let height = 600; let version = 19; let minorVersion = 0; let children = outputElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "movie") { return; } let attributes = child.attributes; if ("platform" in attributes) { let platform = attributes.platform as string; switch (platform) { case "AIR": { result.config = "air"; result.application = "application.xml"; break; } case "AIR Mobile": { result.config = "airmobile"; result.application = "application.xml"; break; } } } else if ("path" in attributes) { let outputPath = attributes.path as string; outputPath = normalizeFilePath(outputPath); if (outputPath.length > 0) { result.compilerOptions.output = outputPath; } } else if ("fps" in attributes) { let fps = parseInt(attributes.fps as string, 10); result.compilerOptions["default-frame-rate"] = fps; } else if ("width" in attributes) { width = parseInt(attributes.width as string, 10); } else if ("height" in attributes) { height = parseInt(attributes.height as string, 10); } else if ("version" in attributes) { version = parseInt(attributes.version as string, 10); } else if ("minorVersion" in attributes) { minorVersion = parseInt(attributes.minorVersion as string, 10); } else if ("background" in attributes) { let backgroundColor = attributes.background as string; result.compilerOptions["default-background-color"] = backgroundColor; } else if ("preferredSDK" in attributes) { let frameworkSDKConfig = vscode.workspace.getConfiguration("as3mxml"); let frameworkSDK = frameworkSDKConfig.inspect("sdk.framework").workspaceValue; if (!frameworkSDK) { let preferredSDK = attributes.preferredSDK as string; let validatedSDKPath = validateFrameworkSDK(preferredSDK); if (validatedSDKPath !== null) { frameworkSDKConfig.update("sdk.framework", validatedSDKPath); } } } }); result.compilerOptions["default-size"] = { width, height }; result.compilerOptions["target-player"] = version + "." + minorVersion; } function migrateBuildElement(buildElement: any, result: any) { let children = buildElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "option") { return; } let attributes = child.attributes; if ("accessible" in attributes) { let accessible = attributes.accessible as string; result.compilerOptions.accessible = accessible === "True"; } else if ("advancedTelemetry" in attributes) { let advancedTelemetry = attributes.advancedTelemetry as string; result.compilerOptions["advanced-telemetry"] = advancedTelemetry === "True"; } //TODO: allowSourcePathOverlap else if ("benchmark" in attributes) { let benchmark = attributes.benchmark as string; result.compilerOptions.benchmark = benchmark === "True"; } //TODO: es //TODO: inline else if ("locale" in attributes) { let locale = attributes.locale as string; if (locale.length > 0) { result.compilerOptions.locale = [locale]; } } else if ("loadConfig" in attributes) { let loadConfig = attributes.loadConfig as string; loadConfig = normalizeFilePath(loadConfig); if (loadConfig.length > 0) { result.compilerOptions["load-config"] = [loadConfig]; } } else if ("optimize" in attributes) { let optimize = attributes.optimize as string; result.compilerOptions.optimize = optimize === "True"; } else if ("omitTraces" in attributes) { let omitTraces = attributes.omitTraces as string; result.compilerOptions["omit-trace-statements"] = omitTraces === "True"; } //TODO: showActionScriptWarnings //TODO: showBindingWarnings //TODO: showInvalidCSS //TODO: showDeprecationWarnings else if ("showUnusedTypeSelectorWarnings" in attributes) { let showUnusedTypeSelectorWarnings = attributes.showUnusedTypeSelectorWarnings as string; result.compilerOptions["show-unused-type-selector-warnings"] = showUnusedTypeSelectorWarnings === "True"; } else if ("strict" in attributes) { let strict = attributes.strict as string; result.compilerOptions.strict = strict === "True"; } else if ("useNetwork" in attributes) { let useNetwork = attributes.useNetwork as string; result.compilerOptions["use-network"] = useNetwork === "True"; } else if ("useResourceBundleMetadata" in attributes) { let useResourceBundleMetadata = attributes.useResourceBundleMetadata as string; result.compilerOptions["use-resource-bundle-metadata"] = useResourceBundleMetadata === "True"; } else if ("warnings" in attributes) { let warnings = attributes.warnings as string; result.compilerOptions.warnings = warnings === "True"; } else if ("verboseStackTraces" in attributes) { let verboseStackTraces = attributes.verboseStackTraces as string; result.compilerOptions["verbose-stacktraces"] = verboseStackTraces === "True"; } else if ("linkReport" in attributes) { let linkReport = attributes.linkReport as string; linkReport = normalizeFilePath(linkReport); if (linkReport.length > 0) { result.compilerOptions["link-report"] = [linkReport]; } } else if ("loadExterns" in attributes) { let loadExterns = attributes.loadExterns as string; loadExterns = normalizeFilePath(loadExterns); if (loadExterns.length > 0) { result.compilerOptions["load-externs"] = [loadExterns]; } } else if ("staticLinkRSL" in attributes) { let staticLinkRSL = attributes.staticLinkRSL as string; result.compilerOptions["static-link-runtime-shared-libraries"] = staticLinkRSL === "True"; } else if ("additional" in attributes) { let additional = attributes.additional as string; if (additional.length > 0) { additional = additional.replace(/\n/g, " "); result.additionalOptions = additional; } } else if ("compilerConstants" in attributes) { let compilerConstants = attributes.compilerConstants as string; if (compilerConstants.length > 0) { let splitConstants = compilerConstants.split("\n"); let define = splitConstants.map((constant) => { let parts = constant.split(","); let name = parts[0]; let valueAsString = parts[1]; let value: any = undefined; if (valueAsString.startsWith('"') && valueAsString.endsWith('"')) { value = valueAsString; } else if ( valueAsString.startsWith("'") && valueAsString.endsWith("'") ) { value = valueAsString; } else if (valueAsString === "true" || valueAsString === "false") { value = valueAsString === "true"; } else if ( /^-?[0-9]+(\.[0-9]+)?([eE](\-|\+)?[0-9]+)?$/.test(valueAsString) ) { value = parseFloat(valueAsString); } else { addWarning(WARNING_INVALID_DEFINE + name); } return { name, value }; }); result.compilerOptions.define = define; } } }); } function migrateLibraryPathsElement(libraryPathsElement: any, result: any) { let libraryPaths = []; let children = libraryPathsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "element") { return; } let attributes = child.attributes; if ("path" in attributes) { let libraryPath = attributes.path as string; libraryPath = normalizeFilePath(libraryPath); if (libraryPath.length > 0) { libraryPaths.push(libraryPath); } } }); if (libraryPaths.length > 0) { result.compilerOptions["library-path"] = libraryPaths; } } function migrateExternalLibraryPathsElement( externalLibraryPathsElement: any, result: any ) { let externalLibraryPaths = []; let children = externalLibraryPathsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "element") { return; } let attributes = child.attributes; if ("path" in attributes) { let externalLibraryPath = attributes.path as string; externalLibraryPath = normalizeFilePath(externalLibraryPath); if (externalLibraryPath.length > 0) { externalLibraryPaths.push(externalLibraryPath); } } }); if (externalLibraryPaths.length > 0) { result.compilerOptions["external-library-path"] = externalLibraryPaths; } } function migrateIncludeLibrariesElement( includeLibrariesElement: any, result: any ) { let includeLibraries = []; let children = includeLibrariesElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "element") { return; } let attributes = child.attributes; if ("path" in attributes) { let includeLibrary = attributes.path as string; includeLibrary = normalizeFilePath(includeLibrary); if (includeLibrary.length > 0) { includeLibraries.push(includeLibrary); } } }); if (includeLibraries.length > 0) { result.compilerOptions["include-libraries"] = includeLibraries; } } function migratePreBuildCommandElement(optionsElement: any, result: any) { let children = optionsElement.children as any[]; if (children.length > 1) { return; } children.forEach((child) => { if (child.type !== "text") { return; } let preBuildCommand = child.text.trim(); if (preBuildCommand.length > 0) { addWarning(WARNING_PRE_BUILD_COMMAND + preBuildCommand); addWarning(WARNING_COMMAND_TASK); } }); } function migratePostBuildCommandElement(optionsElement: any, result: any) { let children = optionsElement.children as any[]; if (children.length > 1) { return; } children.forEach((child) => { if (child.type !== "text") { return; } let postBuildCommand = child.text.trim(); if (postBuildCommand.length > 0) { addWarning(WARNING_POST_BUILD_COMMAND + postBuildCommand); addWarning(WARNING_COMMAND_TASK); } }); } function migrateOptionsElement(optionsElement: any, result: any) { let customTestMovie = false; let testMovieCommand = ""; let children = optionsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" || child.name !== "option") { return; } let attributes = child.attributes; if ("testMovie" in attributes) { customTestMovie = attributes.testMovie === "Custom"; } if ("testMovieCommand" in attributes) { testMovieCommand = attributes.testMovieCommand.trim(); } }); if (customTestMovie && testMovieCommand.length > 0) { addWarning(WARNING_TEST_MOVIE_COMMAND + testMovieCommand); addWarning(WARNING_COMMAND_TASK); } } function migrateRslPathsElement(rslPathsElement: any, result: any) { let children = rslPathsElement.children as any[]; children.forEach((child) => { if (child.type !== "element" && child.name !== "element") { return; } let attributes = child.attributes; if ("path" in attributes) { let rslPath = attributes.path as string; addWarning(WARNING_RSL_PATHS + rslPath); } }); } function migrateLibraryElement(libraryElement: any, result: any) { let children = libraryElement.children as any[]; children.forEach((child) => { if (child.type !== "element" && child.name !== "asset") { return; } let attributes = child.attributes; if ("path" in attributes) { let assetPath = attributes.path as string; addWarning(WARNING_LIBRARY_ASSETS + assetPath); } }); } function normalizeFilePath(filePath: string) { return filePath.replace(/\\/g, "/").trim(); } let outputChannel: vscode.OutputChannel; function getOutputChannel() { if (!outputChannel) { outputChannel = vscode.window.createOutputChannel(CHANNEL_NAME_IMPORTER); } return outputChannel; } function addWarning(message: string) { getOutputChannel().appendLine("🚧 " + message); } function addError(message: string) { getOutputChannel().appendLine("⛔ " + message); } function findChildElementByName(children: any[], name: string) { return children.find((child) => { return child.type === "element" && child.name === name; }); }
the_stack
import { TableClient } from "@azure/data-tables"; import * as assert from "assert"; import { configLogger } from "../../src/common/Logger"; import TableTestServerFactory from "../TableTestServerFactory"; import { generateJWTToken, getUniqueName } from "../testutils"; import { SimpleTokenCredential } from "../simpleTokenCredential"; // Set true to enable debug log configLogger(false); describe("Table OAuth Basic", () => { const factory = new TableTestServerFactory(); let server = factory.createServer(false, false, true, "basic"); const baseURL = `https://${server.config.host}:${server.config.port}/devstoreaccount1`; before(async () => { await server.start(); }); after(async () => { await server.close(); await server.clean(); }); it(`Should work with create table @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://storage.azure.com", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); await tableClient.createTable(); await tableClient.deleteTable(); }); it(`Should not work with invalid JWT token @loki @sql`, async () => { const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential("invalid token"), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); return; } assert.fail(); }); it(`Should work with valid audiences @loki @sql`, async () => { const audiences = [ "https://storage.azure.com", "https://storage.azure.com/", "e406a681-f3d4-42a8-90b6-c2b029497af1", "https://devstoreaccount1.table.core.windows.net", "https://devstoreaccount1.table.core.windows.net/", "https://devstoreaccount1.table.core.chinacloudapi.cn", "https://devstoreaccount1.table.core.chinacloudapi.cn/", "https://devstoreaccount1.table.core.usgovcloudapi.net", "https://devstoreaccount1.table.core.usgovcloudapi.net/", "https://devstoreaccount1.table.core.cloudapi.de", "https://devstoreaccount1.table.core.cloudapi.de/" ]; for (const audience of audiences) { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", audience, "user_impersonation" ); const tableName: string = getUniqueName("ltablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); await tableClient.createTable(); await tableClient.deleteTable(); } }); it(`Should not work with invalid audiences @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://invalidaccount.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("audience"), true); return; } assert.fail(); }); it(`Should work with valid issuers @loki @sql`, async () => { const issuerPrefixes = [ "https://sts.windows.net/", "https://sts.microsoftonline.de/", "https://sts.chinacloudapi.cn/", "https://sts.windows-ppe.net" ]; for (const issuerPrefix of issuerPrefixes) { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), `${issuerPrefix}/ab1f708d-50f6-404c-a006-d71b2ac7a606/`, "e406a681-f3d4-42a8-90b6-c2b029497af1", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); await tableClient.createTable(); await tableClient.deleteTable(); } }); it(`Should not work with invalid issuers @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://invalidissuer/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://invalidaccount.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("issuer"), true); return; } assert.fail(); }); it(`Should not work with invalid nbf @loki @sql`, async () => { const token = generateJWTToken( new Date("2119/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("Lifetime"), true); return; } assert.fail(); }); it(`Should not work with invalid exp @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2019/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("expire"), true); return; } assert.fail(); }); it(`Should not work with get table ACL @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); await tableClient.createTable(); try { await tableClient.getAccessPolicy(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthorizationFailure"), true ); await tableClient.deleteTable(); return; } await tableClient.deleteTable(); assert.fail(); }); it(`Should not work with set table ACL @loki @sql`, async () => { const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2100/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( baseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); await tableClient.createTable(); const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); try { await tableClient.setAccessPolicy([{ id: "test", accessPolicy: { start: now, expiry: tmr, permission: "r" } }]); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthorizationFailure"), true ); await tableClient.deleteTable(); return; } await tableClient.deleteTable(); assert.fail(); }); // skip this test case for it will throw an error when use azure table sdk to connect Azurite table by http it.skip(`Should not work with HTTP @loki @sql`, async () => { await server.close(); await server.clean(); server = factory.createServer(false, false, false, "basic"); await server.start(); const httpBaseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1`; const token = generateJWTToken( new Date("2019/01/01"), new Date("2019/01/01"), new Date("2019/01/01"), "https://sts.windows-ppe.net/ab1f708d-50f6-404c-a006-d71b2ac7a606/", "https://devstoreaccount1.table.core.windows.net", "user_impersonation" ); const tableName: string = getUniqueName("tablewithdash"); const tableClient = new TableClient( httpBaseURL, tableName, new SimpleTokenCredential(token), { redirectOptions: { maxRetries: 1 } } ); try { await tableClient.createTable(); await tableClient.deleteTable(); } catch (err) { assert.deepStrictEqual( err.message.includes("AuthenticationFailed"), true ); assert.deepStrictEqual(err.message.includes("HTTP"), true); return; } assert.fail(); }); });
the_stack
import { Syntax, Visitor, id } from './javascript'; import { MessageException, unexpected } from './message'; import { globalDeclarations } from './preamble'; function unsupportedLoc (loc: Syntax.SourceLocation, description: string = '') { return new MessageException({ status: 'error', type: 'unsupported', loc, description }); } function undefinedId (loc: Syntax.SourceLocation) { return new MessageException({ status: 'error', type: 'undefined-identifier', loc, description: '' }); } function alreadyDefined (loc: Syntax.SourceLocation, decl: Syntax.Declaration) { if (decl.type === 'Unresolved') { throw unexpected(new Error('decl should be resolved')); } const { file, start } = decl.decl.loc; return new MessageException({ status: 'error', type: 'already-defined', loc, description: `at ${file}:${start.line}:${start.column}` }); } function assignToConst (loc: Syntax.SourceLocation) { return new MessageException({ status: 'error', type: 'assignment-to-const', loc, description: '' }); } function refInInvariant (loc: Syntax.SourceLocation) { return new MessageException({ status: 'error', type: 'reference-in-invariant', loc, description: '' }); } export function isMutable (idOrDecl: Syntax.Identifier | Syntax.Declaration): boolean { const decl = idOrDecl.type === 'Identifier' ? idOrDecl.decl : idOrDecl; return decl.type === 'Var' && decl.decl.kind === 'let'; } class Scope { funcOrLoop: Syntax.Function | Syntax.WhileStatement | null; ids: { [varname: string]: Syntax.Declaration } = {}; parent: Scope | null; constructor (parent: Scope | null = null, fw: Syntax.Function | Syntax.WhileStatement | null = null) { this.parent = parent; this.funcOrLoop = fw; } lookupDef (sym: Syntax.Identifier) { if (sym.name in this.ids) throw alreadyDefined(sym.loc, this.ids[sym.name]); if (this.parent) this.parent.lookupDef(sym); } defSymbol (sym: Syntax.Identifier, decl: Syntax.Declaration) { // TODO enable shadowing this.lookupDef(sym); this.ids[sym.name] = decl; } lookupUse (sym: Syntax.Identifier, clz: boolean): Syntax.Declaration { let decl: Syntax.Declaration | null = null; if (sym.name in this.ids) { decl = this.ids[sym.name]; } else if (this.parent) { decl = this.parent.lookupUse(sym, clz); if (this.funcOrLoop && !this.funcOrLoop.freeVars.some(fv => fv.name === sym.name) && isMutable(decl)) { this.funcOrLoop.freeVars.push(sym); // a free variable } } if (!decl || decl.type === 'Unresolved') { throw undefinedId(sym.loc); } if (clz && (decl.type !== 'Class')) throw unsupportedLoc(sym.loc, 'expected class'); if (!clz && (decl.type === 'Class')) throw unsupportedLoc(sym.loc, 'did not expect class'); return decl; } useSymbol (sym: Syntax.Identifier, write: boolean = false, clz: boolean = false, allowRef: boolean = true) { const decl = this.lookupUse(sym, clz); sym.decl = decl; switch (decl.type) { case 'Var': decl.decl.id.refs.push(sym); if (!allowRef) { throw refInInvariant(sym.loc); } if (write) { if (decl.decl.kind === 'const') { throw assignToConst(sym.loc); } decl.decl.id.isWrittenTo = true; } break; case 'Func': if (!decl.decl.id) throw unsupportedLoc(sym.loc, 'function should have name'); decl.decl.id.refs.push(sym); if (write) { throw assignToConst(sym.loc); } break; case 'Param': decl.decl.refs.push(sym); if (write) { throw assignToConst(sym.loc); } break; case 'Class': if (write) { throw assignToConst(sym.loc); } break; } } } class NameResolver extends Visitor<void, void, void, void> { scope: Scope = new Scope(); allowOld: boolean = false; allowRef: boolean = true; scoped (action: () => void, allowsOld: boolean = this.allowOld, allowsRef: boolean = this.allowRef, fn: Syntax.Function | Syntax.WhileStatement | null = this.scope.funcOrLoop) { const { scope, allowOld, allowRef } = this; try { this.scope = new Scope(scope, fn); this.allowOld = allowsOld; this.allowRef = allowsRef; action(); } finally { this.scope = scope; this.allowOld = allowOld; this.allowRef = allowRef; } } visitIdentifierTerm (term: Syntax.Identifier) { this.scope.useSymbol(term, false, false, this.allowRef); } visitOldIdentifierTerm (term: Syntax.OldIdentifier) { if (!this.allowOld) throw unsupportedLoc(term.loc, 'old() not allowed in this context'); this.scope.useSymbol(term.id); } visitLiteralTerm (term: Syntax.Literal) { /* empty */ } visitUnaryTerm (term: Syntax.UnaryTerm) { this.visitTerm(term.argument); } visitBinaryTerm (term: Syntax.BinaryTerm) { this.visitTerm(term.left); this.visitTerm(term.right); } visitLogicalTerm (term: Syntax.LogicalTerm) { this.visitTerm(term.left); this.visitTerm(term.right); } visitConditionalTerm (term: Syntax.ConditionalTerm) { this.visitTerm(term.test); this.visitTerm(term.consequent); this.visitTerm(term.alternate); } visitCallTerm (term: Syntax.CallTerm) { term.args.forEach(e => this.visitTerm(e)); this.visitTerm(term.callee); } visitMemberTerm (term: Syntax.MemberTerm) { this.visitTerm(term.object); this.visitTerm(term.property); } visitIsIntegerTerm (term: Syntax.IsIntegerTerm) { this.visitTerm(term.term); } visitToIntegerTerm (term: Syntax.ToIntegerTerm) { this.visitTerm(term.term); } visitTermAssertion (term: Syntax.Term) { this.visitTerm(term); } visitPureAssertion (assertion: Syntax.PureAssertion) { /* empty */ } visitPostCondition (post: Syntax.PostCondition) { if (post.argument) { // scoped at the surrounding context (spec or function body) this.scope.defSymbol(post.argument, { type: 'PostArg', decl: post }); } this.visitAssertion(post.expression); } visitSpecAssertion (assertion: Syntax.SpecAssertion) { this.visitTerm(assertion.callee); this.scoped(() => { assertion.args.forEach((a, argIdx) => { this.scope.defSymbol(id(a), { type: 'SpecArg', decl: assertion, argIdx }); }); this.visitAssertion(assertion.pre); }, false); this.scoped(() => { assertion.args.forEach((a, argIdx) => { this.scope.defSymbol(id(a), { type: 'SpecArg', decl: assertion, argIdx }); }); this.visitPostCondition(assertion.post); }, true); } visitEveryAssertion (assertion: Syntax.EveryAssertion) { this.visitTerm(assertion.array); this.scoped(() => { this.scope.defSymbol(assertion.argument, { type: 'EveryArg', decl: assertion }); if (assertion.indexArgument !== null) { this.scope.defSymbol(assertion.indexArgument, { type: 'EveryIdxArg', decl: assertion }); } this.visitAssertion(assertion.expression); }, false); } visitInstanceOfAssertion (assertion: Syntax.InstanceOfAssertion) { this.visitTerm(assertion.left); this.scope.useSymbol(assertion.right, false, true); } visitInAssertion (assertion: Syntax.InAssertion) { this.visitTerm(assertion.property); this.visitTerm(assertion.object); } visitUnaryAssertion (assertion: Syntax.UnaryAssertion) { this.visitAssertion(assertion.argument); } visitBinaryAssertion (assertion: Syntax.BinaryAssertion) { this.visitAssertion(assertion.left); this.visitAssertion(assertion.right); } visitIdentifier (expr: Syntax.Identifier) { this.scope.useSymbol(expr, false, false, this.allowRef); } visitLiteral (expr: Syntax.Literal) { /* empty */ } visitUnaryExpression (expr: Syntax.UnaryExpression) { this.visitExpression(expr.argument); } visitBinaryExpression (expr: Syntax.BinaryExpression) { this.visitExpression(expr.left); this.visitExpression(expr.right); } visitLogicalExpression (expr: Syntax.LogicalExpression) { this.visitExpression(expr.left); this.visitExpression(expr.right); } visitConditionalExpression (expr: Syntax.ConditionalExpression) { this.visitExpression(expr.test); this.visitExpression(expr.consequent); this.visitExpression(expr.alternate); } visitAssignmentExpression (expr: Syntax.AssignmentExpression) { this.visitExpression(expr.right); if (expr.left.type !== 'Identifier') throw unsupportedLoc(expr.loc); this.scope.useSymbol(expr.left, true); } visitSequenceExpression (expr: Syntax.SequenceExpression) { expr.expressions.forEach(e => this.visitExpression(e)); } visitCallExpression (expr: Syntax.CallExpression) { expr.args.forEach(e => this.visitExpression(e)); this.visitExpression(expr.callee); } visitNewExpression (expr: Syntax.NewExpression) { this.scope.useSymbol(expr.callee, false, true); expr.args.forEach(e => this.visitExpression(e)); } visitArrayExpression (expr: Syntax.ArrayExpression) { expr.elements.forEach(e => this.visitExpression(e)); } visitObjectExpression (expr: Syntax.ObjectExpression) { expr.properties.forEach(p => this.visitExpression(p.value)); } visitInstanceOfExpression (expr: Syntax.InstanceOfExpression) { this.visitExpression(expr.left); this.scope.useSymbol(expr.right, false, true); } visitInExpression (expr: Syntax.InExpression) { this.visitExpression(expr.property); this.visitExpression(expr.object); } visitMemberExpression (expr: Syntax.MemberExpression) { this.visitExpression(expr.object); this.visitExpression(expr.property); } visitFunctionExpression (expr: Syntax.FunctionExpression) { this.scoped(() => { if (expr.id) this.scope.defSymbol(expr.id, { type: 'Func', decl: expr }); expr.params.forEach(p => this.scope.defSymbol(p, { type: 'Param', func: expr, decl: p })); expr.requires.forEach(r => this.visitAssertion(r)); expr.ensures.forEach(s => { this.scoped(() => this.visitPostCondition(s), true); }); expr.body.body.forEach(s => this.visitStatement(s)); }, false, this.allowRef, expr); } visitVariableDeclaration (stmt: Syntax.VariableDeclaration) { this.scope.defSymbol(stmt.id, { type: 'Var', decl: stmt }); this.visitExpression(stmt.init); } visitBlockStatement (stmt: Syntax.BlockStatement) { this.scoped(() => { stmt.body.forEach(s => this.visitStatement(s)); }); } visitExpressionStatement (stmt: Syntax.ExpressionStatement) { this.visitExpression(stmt.expression); } visitAssertStatement (stmt: Syntax.AssertStatement) { this.visitAssertion(stmt.expression); } visitIfStatement (stmt: Syntax.IfStatement) { this.visitExpression(stmt.test); this.scoped(() => { stmt.consequent.body.forEach(s => this.visitStatement(s)); }); this.scoped(() => { stmt.alternate.body.forEach(s => this.visitStatement(s)); }); } visitReturnStatement (stmt: Syntax.ReturnStatement) { this.visitExpression(stmt.argument); } visitWhileStatement (stmt: Syntax.WhileStatement) { this.scoped(() => { this.visitExpression(stmt.test); stmt.invariants.forEach(i => this.visitAssertion(i)); stmt.body.body.forEach(s => this.visitStatement(s)); }, false, true, stmt); } visitDebuggerStatement (stmt: Syntax.DebuggerStatement) { /* empty */ } visitFunctionDeclaration (stmt: Syntax.FunctionDeclaration) { this.scope.defSymbol(stmt.id, { type: 'Func', decl: stmt }); this.scoped(() => { stmt.params.forEach(p => this.scope.defSymbol(p, { type: 'Param', func: stmt, decl: p })); stmt.requires.forEach(r => this.visitAssertion(r)); stmt.ensures.forEach(s => { this.scoped(() => this.visitPostCondition(s), true); }); stmt.body.body.forEach(s => this.visitStatement(s)); }, false, true, stmt); } visitMethodDeclaration (stmt: Syntax.MethodDeclaration, cls: Syntax.ClassDeclaration) { this.scoped(() => { this.scope.defSymbol(id('this'), { type: 'This', decl: cls }); stmt.params.forEach(p => this.scope.defSymbol(p, { type: 'Param', func: stmt, decl: p })); stmt.requires.forEach(r => this.visitAssertion(r)); stmt.ensures.forEach(s => { this.scoped(() => this.visitPostCondition(s), true); }); stmt.body.body.forEach(s => this.visitStatement(s)); }, false, true, stmt); } visitClassDeclaration (stmt: Syntax.ClassDeclaration) { this.scope.defSymbol(stmt.id, { type: 'Class', decl: stmt }); this.scoped(() => { this.scope.defSymbol(id('this'), { type: 'This', decl: stmt }); this.visitAssertion(stmt.invariant); }, false, false); stmt.methods.forEach(method => this.visitMethodDeclaration(method, stmt)); } visitPreamble () { for (const decl of globalDeclarations()) { this.scope.defSymbol(decl.decl.id, decl); } } visitProgram (prog: Syntax.Program) { prog.body.forEach(stmt => this.visitStatement(stmt)); prog.invariants.forEach(inv => this.visitAssertion(inv)); } } export function resolveNames (program: Syntax.Program, preamble: boolean = true): void { const resolver = new NameResolver(); if (preamble) { resolver.visitPreamble(); } resolver.visitProgram(program); }
the_stack
import dayjs from 'dayjs'; import sample from 'lodash/sample'; import { commands, Position, QuickPickItem, Range, Selection, TextDocument, TextEditor, TextEditorEdit, ThemeIcon, window, WorkspaceEdit } from 'vscode'; import { appendTaskToFile, archiveTasks, editTaskWorkspaceEdit, hideTask, incrementCountForTask, incrementOrDecrementPriority, removeOverdueWorkspaceEdit, resetAllRecurringTasks, revealTask, setDueDate, startTask, toggleCommentAtLineWorkspaceEdit, toggleDoneAtLine, toggleDoneOrIncrementCount, toggleTaskCollapseWorkspaceEdit, tryToDeleteTask } from './documentActions'; import { DueDate } from './dueDate'; import { updateEverything } from './events'; import { Constants, extensionConfig, extensionState, Global, updateLastVisitGlobalState, updateState } from './extension'; import { defaultSortTasks, SortProperty, sortTasks } from './sort'; import { TheTask } from './TheTask'; import { helpCreateDueDate } from './time/setDueDateHelper'; import { getDateInISOFormat } from './time/timeUtils'; import { TaskTreeItem } from './treeViewProviders/taskProvider'; import { getArchivedDocument, tasksView, updateAllTreeViews, updateTasksTreeView } from './treeViewProviders/treeViews'; import { CommandIds, TreeItemSortType, VscodeContext } from './types'; import { applyEdit, checkArchiveFileAndNotify, checkDefaultFileAndNotify, getActiveOrDefaultDocument, specifyDefaultArchiveFile, specifyDefaultFile } from './utils/extensionUtils'; import { forEachTask, formatTask, getTaskAtLineExtension } from './utils/taskUtils'; import { fancyNumber, unique } from './utils/utils'; import { followLink, followLinks, getFullRangeFromLines, inputOffset, openFileInEditor, openInUntitled, openSettingsGuiAt, setContext, toggleGlobalSetting, updateSetting } from './utils/vscodeUtils'; /** * Register all commands. Names should match **"commands"** in `package.json` */ export function registerAllCommands() { commands.registerCommand(CommandIds.toggleDone, async (treeItem?: TaskTreeItem) => { const editor = window.activeTextEditor; let document: TextDocument; let lineNumbers: number[] = []; if (treeItem) { lineNumbers.push(treeItem.task.lineNumber); document = await getActiveOrDefaultDocument(); } else { if (!editor) { return; } lineNumbers = getSelectedLineNumbers(editor); document = editor.document; } for (const ln of lineNumbers) { await toggleDoneOrIncrementCount(document, ln); } await updateState(); updateAllTreeViews(); }); commands.registerCommand(CommandIds.hideTask, async (treeItem?: TaskTreeItem) => { if (!treeItem) { return; } const lineNumber = treeItem.task.lineNumber; const document = await getActiveOrDefaultDocument(); hideTask(document, lineNumber); await updateState(); updateAllTreeViews(); }); commands.registerCommand(CommandIds.collapseAllNestedTasks, async () => { const edit = new WorkspaceEdit(); const activeDocument = await getActiveOrDefaultDocument(); forEachTask(task => { if (TheTask.hasNestedTasks(task) && !task.isCollapsed) { toggleTaskCollapseWorkspaceEdit(edit, activeDocument, task.lineNumber); } }); await applyEdit(edit, activeDocument); updateEverything(); }); commands.registerCommand(CommandIds.expandAllTasks, async () => { const edit = new WorkspaceEdit(); const activeDocument = await getActiveOrDefaultDocument(); forEachTask(task => { if (TheTask.hasNestedTasks(task) && task.isCollapsed) { toggleTaskCollapseWorkspaceEdit(edit, activeDocument, task.lineNumber); } }); await applyEdit(edit, activeDocument); updateEverything(); }); commands.registerCommand(CommandIds.focusTasksWebviewAndInput, async () => { await commands.executeCommand('todomd.webviewTasks.focus'); Global.webviewProvider.focusFilterInput(); }); commands.registerCommand(CommandIds.deleteTask, async (treeItem?: TaskTreeItem) => { if (!treeItem) { return; } const lineNumber = treeItem.task.lineNumber; const document = await getActiveOrDefaultDocument(); await tryToDeleteTask(document, lineNumber); await updateState(); updateAllTreeViews(); }); commands.registerTextEditorCommand(CommandIds.archiveCompletedTasks, editor => { const selection = editor.selection; if (selection.isEmpty) { // Archive all completed tasks const completedTasks = extensionState.tasks.filter(t => t.done); archiveTasks(completedTasks, editor.document); } else { // Archive only selected completed tasks const selectedCompletedTasks = []; for (let i = selection.start.line; i <= selection.end.line; i++) { const task = getTaskAtLineExtension(i); if (task && task.done) { selectedCompletedTasks.push(task); } } archiveTasks(selectedCompletedTasks, editor.document); } }); commands.registerCommand(CommandIds.startTask, async (taskTreeItem?: TaskTreeItem) => { let lineNumber: number; let document: TextDocument; if (taskTreeItem) { lineNumber = taskTreeItem.task.lineNumber; document = await getActiveOrDefaultDocument(); } else { const editor = window.activeTextEditor; if (!editor) { return; } lineNumber = editor.selection.start.line; document = editor.document; } startTask(document, lineNumber); }); commands.registerTextEditorCommand(CommandIds.sortByPriority, (editor, edit) => { sortTasksInEditor(editor, edit, 'priority'); }); commands.registerTextEditorCommand(CommandIds.sortByDefault, (editor, edit) => { sortTasksInEditor(editor, edit, 'default'); }); commands.registerTextEditorCommand(CommandIds.createSimilarTask, async editor => { // Create a task with all the tags, projects and contexts of another task const selection = editor.selection; const task = getTaskAtLineExtension(selection.start.line); if (!task) { return; } const line = editor.document.lineAt(task.lineNumber); const edit = new WorkspaceEdit(); const tagsAsString = task.tags.map(tag => ` #${tag}`).join(''); const projectsAsString = task.projects.map(project => `+${project}`).join(' '); const contextsAsString = task.contexts.map(context => `@${context}`).join(' '); let newTaskAsString = tagsAsString; newTaskAsString += projectsAsString ? ` ${projectsAsString}` : ''; newTaskAsString += contextsAsString ? ` ${contextsAsString}` : ''; edit.insert(editor.document.uri, new Position(line.rangeIncludingLineBreak.end.line, line.rangeIncludingLineBreak.end.character), `${newTaskAsString}\n`); await applyEdit(edit, editor.document); editor.selection = new Selection(line.lineNumber + 1, 0, line.lineNumber + 1, 0); }); commands.registerCommand(CommandIds.getNextTask, async () => { await updateState(); const tasks = extensionState.tasks.filter(t => !t.done); if (!tasks.length) { window.showInformationMessage('No tasks'); return; } const sortedTasks = defaultSortTasks(tasks); const task = sortedTasks[0]; showTaskInNotification(task); }); commands.registerCommand(CommandIds.getFewNextTasks, async () => { await updateState(); const tasks = extensionState.tasks.filter(t => !t.done); if (!tasks.length) { window.showInformationMessage('No tasks'); return; } const sortedTasks = defaultSortTasks(tasks) .slice(0, extensionConfig.getNextNumberOfTasks); window.showInformationMessage(sortedTasks.map((task, i) => `${fancyNumber(i + 1)} ${formatTask(task)}`).join('\n'), { modal: true, }); }); commands.registerCommand(CommandIds.getRandomTask, async () => { await updateState(); const tasks = extensionState.tasks.filter(t => !t.done); if (!tasks.length) { window.showInformationMessage('No tasks'); return; } const randomTask = sample(tasks)!; showTaskInNotification(randomTask); }); commands.registerCommand(CommandIds.addTaskToDefaultFile, async () => { const isDefaultFileSpecified = await checkDefaultFileAndNotify(); if (!isDefaultFileSpecified) { return; } const text = await window.showInputBox({ prompt: 'Add a task to default file', }); if (!text) { return; } await addTaskToFile(text, extensionConfig.defaultFile); await updateState(); updateAllTreeViews(); }); commands.registerCommand(CommandIds.addTaskToActiveFile, async () => { const activeFilePath = extensionState.activeDocument?.uri.fsPath; if (!activeFilePath) { return; } const text = await window.showInputBox({ prompt: 'Add a task to active file', }); if (!text) { return; } addTaskToFile(text, activeFilePath); await updateState(); updateAllTreeViews(); }); commands.registerTextEditorCommand(CommandIds.setDueDate, editor => { openSetDueDateInputbox(editor.document, editor.selection.active.line); }); commands.registerCommand(CommandIds.setDueDateWithArgs, async (document: TextDocument, wordRange: Range, dueDate: string) => { const lineNumber = wordRange.start.line; const edit = new WorkspaceEdit(); edit.delete(document.uri, wordRange); await applyEdit(edit, document); setDueDate(document, lineNumber, dueDate); }); commands.registerCommand(CommandIds.openDefaultArchiveFile, async () => { const isDefaultArchiveFileSpecified = await checkArchiveFileAndNotify(); if (!isDefaultArchiveFileSpecified) { return; } openFileInEditor(extensionConfig.defaultArchiveFile); }); commands.registerCommand(CommandIds.openDefaultFile, async () => { const isDefaultFileSpecified = await checkDefaultFileAndNotify(); if (!isDefaultFileSpecified) { return; } openFileInEditor(extensionConfig.defaultFile); }); commands.registerCommand(CommandIds.specifyDefaultFile, async () => { await specifyDefaultFile(); await commands.executeCommand('list.focusDown');// Workaround for https://github.com/microsoft/vscode/issues/126782 }); commands.registerCommand(CommandIds.specifyDefaultArchiveFile, async () => { await specifyDefaultArchiveFile(); await commands.executeCommand('list.focusDown'); }); commands.registerCommand(CommandIds.completeTask, async () => { // Show Quick Pick to complete a task const document = await getActiveOrDefaultDocument(); // TODO: should this be tree? const notCompletedTasks = defaultSortTasks(extensionState.tasks.filter(task => !task.done)).map(task => ({ label: formatTask(task), ln: task.lineNumber, })); const qp = window.createQuickPick(); qp.title = 'Complete a task'; qp.placeholder = 'Choose a task to complete'; qp.items = notCompletedTasks; const enum Buttons { followLinkBtn = 'Follow link', revealTaskBtn = 'Reveal task', } qp.buttons = [ { iconPath: new ThemeIcon('link-external'), tooltip: Buttons.followLinkBtn, }, { iconPath: new ThemeIcon('go-to-file'), tooltip: Buttons.revealTaskBtn, }, ]; let activeQuickPickItem: typeof notCompletedTasks[0]; qp.onDidChangeActive(e => { // @ts-ignore activeQuickPickItem = e[0]; }); qp.onDidTriggerButton(e => { const task = getTaskAtLineExtension(activeQuickPickItem.ln); if (!task) { return; } if (e.tooltip === Buttons.followLinkBtn) { followLinks(task.links); } else if (e.tooltip === Buttons.revealTaskBtn) { revealTask(task.lineNumber); } qp.hide(); qp.dispose(); }); qp.onDidAccept(async e => { const task = getTaskAtLineExtension(activeQuickPickItem.ln); if (!task) { return; } if (task.count) { await incrementCountForTask(document, task.lineNumber, task); } else { await toggleDoneAtLine(document, task.lineNumber); } await updateState(); updateAllTreeViews(); qp.dispose(); }); qp.show(); }); commands.registerTextEditorCommand(CommandIds.filter, editor => { const quickPick = window.createQuickPick(); quickPick.items = extensionConfig.savedFilters.map(filter => ({ label: filter.title, }) as QuickPickItem); let value: string | undefined; let selected: string | undefined; quickPick.onDidChangeValue(e => { value = e; }); quickPick.onDidChangeSelection(e => { selected = e[0].label; }); quickPick.show(); quickPick.onDidAccept(() => { let filterStr; if (selected) { filterStr = extensionConfig.savedFilters.find(filter => filter.title === selected)?.filter; } else { filterStr = value; } quickPick.hide(); quickPick.dispose(); if (!filterStr || !filterStr.length) { return; } tasksView.description = filterStr; setContext(VscodeContext.filterActive, true); extensionState.taskTreeViewFilterValue = filterStr; updateTasksTreeView(); }); }); commands.registerCommand(CommandIds.clearFilter, editor => { tasksView.description = undefined; setContext(VscodeContext.filterActive, false); extensionState.taskTreeViewFilterValue = ''; updateTasksTreeView(); }); commands.registerCommand(CommandIds.clearGlobalState, () => { (extensionState.extensionContext.globalState as any)._value = {}; extensionState.extensionContext.globalState.update('hack', 'toClear');// Required to clear state }); commands.registerCommand(CommandIds.showGlobalState, () => { const lastVisitByFile = extensionState.extensionContext.globalState.get(Constants.LAST_VISIT_BY_FILE_STORAGE_KEY) as typeof extensionState['lastVisitByFile']; let str = ''; for (const key in lastVisitByFile) { str += `${new Date(lastVisitByFile[key])} | ${dayjs().to(lastVisitByFile[key])} | ${key}\n` ; } openInUntitled(str); }); commands.registerCommand(CommandIds.removeAllOverdue, async () => { const activeDocument = await getActiveOrDefaultDocument(); if (!activeDocument) { return; } const edit = new WorkspaceEdit(); forEachTask(task => { if (task.overdueRange) { removeOverdueWorkspaceEdit(edit, activeDocument.uri, task); } }); applyEdit(edit, activeDocument); }); commands.registerCommand(CommandIds.goToLine, (lineNumber: number) => { revealTask(lineNumber); }); commands.registerCommand(CommandIds.goToLineInArchived, async (lineNumber: number) => { revealTask(lineNumber, await getArchivedDocument()); }); commands.registerTextEditorCommand(CommandIds.resetAllRecurringTasks, editor => { const lastVisit = extensionState.lastVisitByFile[editor.document.uri.toString()]; resetAllRecurringTasks(editor.document, lastVisit); }); commands.registerCommand(CommandIds.followLink, (treeItem: TaskTreeItem) => { followLinks(treeItem.task.links); }); commands.registerTextEditorCommand(CommandIds.setLastVisit, async editor => { const numberOfHours = Number(await window.showInputBox({ prompt: 'Number of Hours ago', })); if (!numberOfHours) { return; } updateLastVisitGlobalState(editor.document.uri.toString(), dayjs().subtract(numberOfHours, 'hour').toDate()); }); commands.registerTextEditorCommand(CommandIds.incrementPriority, editor => { const lineNumber = editor.selection.active.line; incrementOrDecrementPriority(editor.document, lineNumber, 'increment'); }); commands.registerTextEditorCommand(CommandIds.decrementPriority, editor => { const lineNumber = editor.selection.active.line; incrementOrDecrementPriority(editor.document, lineNumber, 'decrement'); }); commands.registerCommand(CommandIds.showWebviewSettings, (treeItem: TaskTreeItem) => { openSettingsGuiAt('todomd.webview'); }); commands.registerCommand(CommandIds.showDefaultFileSetting, (treeItem: TaskTreeItem) => { openSettingsGuiAt(Constants.defaultFileSetting); }); commands.registerCommand(CommandIds.webviewToggleShowRecurringUpcoming, () => { updateSetting('todomd.webview.showRecurringUpcoming', !extensionConfig.webview.showRecurringUpcoming); }); commands.registerTextEditorCommand(CommandIds.toggleComment, editor => { const edit = new WorkspaceEdit(); const selections = editor.selections; for (const selection of selections) { const start = selection.start.line; const end = selection.end.line; for (let i = start; i <= end; i++) { toggleCommentAtLineWorkspaceEdit(edit, editor.document, i); } } applyEdit(edit, editor.document); }); commands.registerCommand(CommandIds.toggleTagsTreeViewSorting, () => { toggleGlobalSetting('todomd.sortTagsView', [TreeItemSortType.alphabetic, TreeItemSortType.count]); }); commands.registerCommand(CommandIds.toggleProjectsTreeViewSorting, () => { toggleGlobalSetting('todomd.sortProjectsView', [TreeItemSortType.alphabetic, TreeItemSortType.count]); }); commands.registerCommand(CommandIds.toggleContextsTreeViewSorting, () => { toggleGlobalSetting('todomd.sortContextsView', [TreeItemSortType.alphabetic, TreeItemSortType.count]); }); // ──── Dev ───────────────────────────────────────────────────────────── commands.registerTextEditorCommand(CommandIds.replaceWithToday, editor => { const wordRange = editor.document.getWordRangeAtPosition(editor.selection.active, /\d{4}-\d{2}-\d{2}/); if (!wordRange) { return; } editor.edit(builder => { builder.replace(wordRange, getDateInISOFormat()); }); }); // ────────────────────────────────────────────────────────────────────── commands.registerTextEditorCommand(CommandIds.sortTaskParts, async editor => { const lineNumbers = getSelectedLineNumbers(editor); const edit = new WorkspaceEdit(); for (const ln of lineNumbers) { const task = getTaskAtLineExtension(ln); if (!task) { continue; } editTaskWorkspaceEdit(edit, editor.document, task); } await applyEdit(edit, editor.document); }); // ──────────────────────────────────────────────────────────── } /** * Append task to the file. * * Optionally adds creation date if user configured `addCreationDate`. */ async function addTaskToFile(text: string, filePath: string) { const creationDate = extensionConfig.addCreationDate ? `{cr:${getDateInISOFormat(new Date(), extensionConfig.creationDateIncludeTime)}} ` : ''; return await appendTaskToFile(`${creationDate}${text}`, filePath); } /** * Show formatted task in notification. Also show button to Follow link if links are present in this task. */ async function showTaskInNotification(task: TheTask) { const formattedTask = formatTask(task); if (task.links.length) { const buttonFollowLink = 'Follow link'; const shouldFollow = await window.showInformationMessage(formattedTask, buttonFollowLink); if (shouldFollow === buttonFollowLink) { followLinks(task.links); } } else { window.showInformationMessage(formattedTask); } } function getSelectedLineNumbers(editor: TextEditor): number[] { const lineNumbers: number[] = []; for (const selection of editor.selections) { for (let i = selection.start.line; i <= selection.end.line; i++) { lineNumbers.push(i); } } return unique(lineNumbers); } /** * Sort tasks in editor. Default sort is by due date. Same due date sorted by priority. */ function sortTasksInEditor(editor: TextEditor, edit: TextEditorEdit, sortProperty: 'default' | 'priority') { const selection = editor.selection; let lineStart = selection.start.line; let lineEnd = selection.end.line; if (selection.isEmpty) { lineStart = 0; lineEnd = editor.document.lineCount - 1; } const tasks: TheTask[] = []; for (let i = lineStart; i <= lineEnd; i++) { const task = getTaskAtLineExtension(i); if (task) { tasks.push(task); } } let sortedTasks: TheTask[]; if (sortProperty === 'priority') { sortedTasks = sortTasks(tasks, SortProperty.priority); } else { sortedTasks = defaultSortTasks(tasks); } const result = sortedTasks.map(t => t.rawText).join('\n'); edit.replace(getFullRangeFromLines(editor.document, lineStart, lineEnd), result); } /** * Open vscode input box that aids in creating of due date. */ export function openSetDueDateInputbox(document: TextDocument, lineNumber: number) { const inputBox = window.createInputBox(); let value: string | undefined = '+0'; inputBox.value = value; inputBox.title = 'Set due date'; const docsButtonName = 'Documentation'; inputBox.onDidTriggerButton(e => { if (e.tooltip === docsButtonName) { followLink('https://github.com/usernamehw/vscode-todo-md/blob/master/docs/docs.md#set-due-date-helper-function-todomdsetduedate'); } }); inputBox.buttons = [{ iconPath: new ThemeIcon('question'), tooltip: docsButtonName, }]; inputBox.prompt = inputOffset(new DueDate(helpCreateDueDate(value)!).closestDueDateInTheFuture); inputBox.show(); inputBox.onDidChangeValue((e: string) => { value = e; const newDueDate = helpCreateDueDate(value); if (!newDueDate) { inputBox.prompt = inputOffset('❌'); return; } inputBox.prompt = inputOffset(new DueDate(newDueDate).closestDueDateInTheFuture); }); inputBox.onDidAccept(async () => { if (!value) { return; } const newDueDate = helpCreateDueDate(value); if (newDueDate) { await setDueDate(document, lineNumber, newDueDate); inputBox.hide(); inputBox.dispose(); updateEverything(); } }); }
the_stack
import { PluginSettingTab, Setting } from 'obsidian'; import BannersPlugin from './main'; type StyleOption = 'solid' | 'gradient'; type IconHorizontalOption = 'left' | 'center' | 'right' | 'custom'; type IconVerticalOption = 'above' | 'center' | 'below' | 'custom'; export interface SettingsOptions { height: number, style: StyleOption, showInInternalEmbed: boolean, internalEmbedHeight: number, showInPreviewEmbed: boolean, previewEmbedHeight: number, frontmatterField: string, iconHorizontalAlignment: IconHorizontalOption, iconHorizontalTransform: string, iconVerticalAlignment: IconVerticalOption, iconVerticalTransform: string, useTwemoji: boolean, showPreviewInLocalModal: boolean, localSuggestionsLimit: number, bannersFolder: string, allowMobileDrag: boolean }; export const INITIAL_SETTINGS: SettingsOptions = { height: null, style: 'solid', showInInternalEmbed: true, internalEmbedHeight: null, showInPreviewEmbed: true, previewEmbedHeight: null, frontmatterField: null, iconHorizontalAlignment: 'left', iconHorizontalTransform: null, iconVerticalAlignment: 'center', iconVerticalTransform: null, useTwemoji: true, showPreviewInLocalModal: true, localSuggestionsLimit: null, bannersFolder: null, allowMobileDrag: false }; export const DEFAULT_VALUES: Partial<SettingsOptions> = { height: 250, internalEmbedHeight: 200, previewEmbedHeight: 120, frontmatterField: 'banner', iconHorizontalTransform: '0px', iconVerticalTransform: '0px', localSuggestionsLimit: 10, bannersFolder: '/' }; const STYLE_OPTIONS: Record<StyleOption, string> = { solid: 'Solid', gradient: 'Gradient' }; const ICON_HORIZONTAL_OPTIONS: Record<IconHorizontalOption, string> = { left: 'Left', center: 'Center', right: 'Right', custom: 'Custom' }; const ICON_VERTICAL_OPTIONS: Record<IconVerticalOption, string> = { above: 'Above', center: 'Center', below: 'Below', custom: 'Custom' }; export default class SettingsTab extends PluginSettingTab { plugin: BannersPlugin; constructor(plugin: BannersPlugin) { super(plugin.app, plugin); this.plugin = plugin; this.containerEl.addClass('banner-settings'); } async saveSettings(changed: Partial<SettingsOptions>, { reloadSettings = false, refreshViews = false } = {}) { this.plugin.settings = { ...this.plugin.settings, ...changed }; await this.plugin.saveData(this.plugin.settings); this.plugin.loadStyles(); if (reloadSettings) { this.display() } if (refreshViews) { this.plugin.refreshViews() } } display() { const { containerEl } = this; const { height, style, showInInternalEmbed, internalEmbedHeight, showInPreviewEmbed, previewEmbedHeight, frontmatterField, iconHorizontalAlignment, iconHorizontalTransform, iconVerticalAlignment, iconVerticalTransform, useTwemoji, showPreviewInLocalModal, localSuggestionsLimit, bannersFolder, allowMobileDrag } = this.plugin.settings; containerEl.empty(); this.createHeader( "Banners", "A nice, lil' thing to add some flair to your notes" ); // Banner height new Setting(containerEl) .setName('Banner height') .setDesc('Set how big the banner should be in pixels') .addText(text => { text.inputEl.type = 'number'; text.setValue(`${height}`); text.setPlaceholder(`${DEFAULT_VALUES.height}`); text.onChange(async (val) => this.saveSettings({ height: val ? parseInt(val) : null })); }); // Banner style new Setting(containerEl) .setName('Banner style') .setDesc('Set a style for all of your banners') .addDropdown(dropdown => dropdown .addOptions(STYLE_OPTIONS) .setValue(style) .onChange(async (val: StyleOption) => this.saveSettings({ style: val }, { refreshViews: true }))); // Show banner in internal embed new Setting(containerEl) .setName('Show banner in internal embed') .setDesc(createFragment(frag => { frag.appendText('Choose whether to display the banner in the internal embed. This is the embed that appears when you write '); frag.createEl('code', { text: '![[file]]' }); frag.appendText(' in a file'); })) .addToggle(toggle => toggle .setValue(showInInternalEmbed) .onChange(async (val) => this.saveSettings({ showInInternalEmbed: val }, { reloadSettings: true, refreshViews: true }))); // Internal embed banner height if (this.plugin.settings.showInInternalEmbed) { new Setting(containerEl) .setName('Internal embed banner height') .setDesc('Set the banner size inside the internal embed') .addText(text => { text.inputEl.type = 'number'; text.setValue(`${internalEmbedHeight}`); text.setPlaceholder(`${DEFAULT_VALUES.internalEmbedHeight}`); text.onChange(async (val) => this.saveSettings({ internalEmbedHeight: val ? parseInt(val) : null })); }); } // Show banner in preview embed new Setting(containerEl) .setName('Show banner in preview embed') .setDesc(createFragment(frag => { frag.appendText('Choose whether to display the banner in the page preview embed. This is the embed that appears from the '); frag.createEl('span', { text: 'Page Preview ', attr: { style: 'color: --var(text-normal)' }}); frag.appendText('core plugin') })) .addToggle(toggle => toggle .setValue(showInPreviewEmbed) .onChange(async (val) => this.saveSettings({ showInPreviewEmbed: val }, { reloadSettings: true }))); // Preview embed banner height if (this.plugin.settings.showInPreviewEmbed) { new Setting(containerEl) .setName('Preview embed banner height') .setDesc('Set the banner size inside the page preview embed') .addText(text => { text.inputEl.type = 'number'; text.setValue(`${previewEmbedHeight}`); text.setPlaceholder(`${DEFAULT_VALUES.previewEmbedHeight}`); text.onChange(async (val) => this.saveSettings({ previewEmbedHeight: val ? parseInt(val) : null })); }); } // Customizable banner metadata fields new Setting(containerEl) .setName('Frontmatter field name') .setDesc(createFragment(frag => { frag.appendText('Set a customizable frontmatter field to use for banner data.'); frag.createEl('br'); frag.appendText('For example, the default value '); frag.createEl('code', { text: DEFAULT_VALUES.frontmatterField }); frag.appendText(' will use the fields '); frag.createEl('code', { text: DEFAULT_VALUES.frontmatterField }); frag.appendText(', '); frag.createEl('code', { text: `${DEFAULT_VALUES.frontmatterField}_x` }); frag.appendText(', '); frag.createEl('code', { text: `${DEFAULT_VALUES.frontmatterField}_y` }); frag.appendText(', and so on...'); })) .addText(text => text .setValue(frontmatterField) .setPlaceholder(DEFAULT_VALUES.frontmatterField) .onChange(async (val) => this.saveSettings({ frontmatterField: val || null }, { refreshViews: true }))); this.createHeader( 'Banner Icons', 'Give people a lil\' notion of what your note is about' ); // Horizontal icon alignment const settingHIA = new Setting(containerEl) .setName('Horizontal alignment') .setDesc(createFragment(frag => { frag.appendText('Align the icon horizontally.'); frag.createEl('br');; frag.appendText('If set to '); frag.createEl('b', { text: 'Custom' }); frag.appendText(', you can set an offset, relative to the left side of the note. This can be any valid '); frag.createEl('a', { text: 'CSS length value', href: 'https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#lengths' }); frag.appendText(', such as '); frag.createEl('code', { text: '10px' }); frag.appendText(', '); frag.createEl('code', { text: '-30%' }); frag.appendText(', '); frag.createEl('code', { text: 'calc(1em + 10px)' }); frag.appendText(', and so on...'); })); if (iconHorizontalAlignment === 'custom') { settingHIA.addText(text => text .setValue(iconHorizontalTransform) .setPlaceholder(DEFAULT_VALUES.iconHorizontalTransform) .onChange(async (val) => this.saveSettings({ iconHorizontalTransform: val || null }, { refreshViews: true }))); } settingHIA.addDropdown(dd => dd .addOptions(ICON_HORIZONTAL_OPTIONS) .setValue(iconHorizontalAlignment) .onChange(async (val: IconHorizontalOption) => this.saveSettings({ iconHorizontalAlignment: val }, { reloadSettings: true, refreshViews: true }))); // Vertical icon alignment const settingVIA = new Setting(containerEl) .setName('Vertical alignment') .setDesc(createFragment(frag => { frag.appendText('Align the icon vertically, relative to a banner (if any).'); frag.createEl('br');; frag.appendText('If set to '); frag.createEl('b', { text: 'Custom' }); frag.appendText(', you can set an offset, relative to the center of a banner\'s lower edge. This follows the same format as the setting above.'); })); if (iconVerticalAlignment === 'custom') { settingVIA.addText(text => text .setValue(iconVerticalTransform) .setPlaceholder(DEFAULT_VALUES.iconVerticalTransform) .onChange(async (val) => this.saveSettings({ iconVerticalTransform: val || null }, { refreshViews: true }))); } settingVIA.addDropdown(dd => dd .addOptions(ICON_VERTICAL_OPTIONS) .setValue(iconVerticalAlignment) .onChange(async (val: IconVerticalOption) => this.saveSettings({ iconVerticalAlignment: val }, { reloadSettings: true, refreshViews: true }))); new Setting(containerEl) .setName('Use Twemoji') .setDesc(createFragment(frag => { frag.appendText('Twitter\'s emoji have better support here. '); frag.createEl('b', { text: 'NOTE: ' }) frag.appendText('This is only applied in the Icon modal and the banner icon in the preview view'); })) .addToggle(toggle => toggle .setValue(useTwemoji) .onChange(async (val) => this.saveSettings({ useTwemoji: val }, { refreshViews: true }))); this.createHeader( 'Local Image Modal', 'For the modal that shows when you run the "Add/Change banner with local image" command' ); // Show preview images in local image modal new Setting(containerEl) .setName('Show preview images') .setDesc('Enabling this will display a preview of the images suggested') .addToggle(toggle => toggle .setValue(showPreviewInLocalModal) .onChange(async (val) => this.saveSettings({ showPreviewInLocalModal: val }))); // Limit of suggestions in local image modal new Setting(containerEl) .setName('Suggestions limit') .setDesc(createFragment(frag => { frag.appendText('Show up to this many suggestions when searching through local images.'); frag.createEl('br'); frag.createEl('b', { text: 'NOTE: '}); frag.appendText('Using a high number while '); frag.createEl('span', { text: 'Show preview images ', attr: { style: 'color: var(--text-normal)' } }); frag.appendText('is on can lead to some slowdowns'); })) .addText(text => { text.inputEl.type = 'number'; text.setValue(`${localSuggestionsLimit}`); text.setPlaceholder(`${DEFAULT_VALUES.localSuggestionsLimit}`); text.onChange(async (val) => this.saveSettings({ localSuggestionsLimit: val ? parseInt(val) : null })); }); // Search in a specific folder for banners new Setting(containerEl) .setName('Banners folder') .setDesc(createFragment(frag => { frag.appendText('Select a folder to exclusively search for banner files in.'); frag.createEl('br'); frag.appendText('If empty, it will search the entire vault for image files'); })) .addText(text => text .setValue(bannersFolder) .setPlaceholder(DEFAULT_VALUES.bannersFolder) .onChange(async (val) => this.saveSettings({ bannersFolder: val || null } ))); this.createHeader( 'Experimental Things', 'Not as well-tested and probably finicky' ); // Drag banners in mobile new Setting(containerEl) .setName('Allow mobile drag') .setDesc(createFragment(frag => { frag.appendText('Allow dragging the banner on mobile devices.'); frag.createEl('br'); frag.createEl('b', { text: 'NOTE: ' }); frag.appendText('App reload might be necessary'); })) .addToggle(toggle => toggle .setValue(allowMobileDrag) .onChange(async (val) => this.saveSettings({ allowMobileDrag: val }, { refreshViews: true }))); } createHeader(text: string, desc: string = null) { const header = this.containerEl.createDiv({ cls: 'setting-item setting-item-heading banner-setting-header' }); header.createEl('p', { text, cls: 'banner-setting-header-title' }); if (desc) { header.createEl('p', { text: desc, cls: 'banner-setting-header-description' }); } } }
the_stack
import { Obligation, ProjectScanStatusType, Scan, SystemConfiguration } from '@app/models'; import { ProjectAttributionDto, ProjectDistinctLicenseDto, ProjectDistinctVulnerabilityDto } from '@app/models/DTOs'; import { ObligationSearchDto } from '@app/models/DTOs/ObligationSearchDto'; import { ProjectDistinctSeverityDto } from '@app/models/DTOs/ProjectDistinctSeverityDto'; import { Project } from '@app/models/Project'; import { AppServiceBase } from '@app/services/app-service-base/app-base.service'; import { BomManualLicenseService } from '@app/services/bom-manual-license/bom-manual-license.service'; import { ProjectAttributionService } from '@app/services/project-attribution/project-attribution.service'; import { ProjectScanStatusTypeService } from '@app/services/project-scan-status-type/project-scan-status-type.service'; import { ScanService } from '@app/services/scan/scan.service'; import { PaginateRawQuery } from '@app/shared/util/paginate-array-result'; import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { CrudRequestOptions, GetManyDefaultResponse } from '@nestjsx/crud'; import { ParsedRequestParams } from '@nestjsx/crud-request'; import { logger } from 'elastic-apm-node'; import { SelectQueryBuilder } from 'typeorm'; import * as url from 'url'; import { debug } from 'winston'; @Injectable() export class ProjectService extends AppServiceBase<Project> { constructor( @Inject(forwardRef(() => ScanService)) private readonly scanService: ScanService, @Inject(forwardRef(() => BomManualLicenseService)) private readonly bomManualLicenseService: BomManualLicenseService, @Inject(forwardRef(() => ProjectAttributionService)) private readonly projectAttributionService: ProjectAttributionService, @InjectRepository(Project) repo, ) { super(repo); } /** * Gets distinct licenses from the latest Scan of a Project */ async distinctLicenses(project: Project): Promise<ProjectDistinctLicenseDto[]> { const query = ` select l.name, count(*) from license l, ( select lsri."licenseId" as licenseId from license_scan_result_item lsri, license_scan_result lsr, scan s where lsri."licenseScanId" = lsr.id and lsr."scanId" = s.id and s.id = (select s2.id from scan s2 where s2."projectId" = $1 order by s2.completed_at desc limit 1) and lsr.id = (select lsr2.id from license_scan_result lsr2 where lsr2."scanId" = (select s2.id from scan s2 where s2."projectId" = $1 order by s2.completed_at desc limit 1) order by s.completed_at desc limit 1) union all select bml."licenseId" as licenseId from bom_manual_license bml where bml."projectId" = $1) t where l.id = t.licenseId group by l.id`; const rows = await this.db.manager.query(query, [project.id]); return rows.map((row) => ({ license: { name: row.name, }, count: row.count, })); } /** * Gets distinct obligations from the latest Scan of a Project */ async distinctObligations(project: Project): Promise<Obligation[]> { const scan = await this.latestCompletedScan(project); if (scan) { return this.scanService.distinctObligations(scan); } else { return []; } } /** * Gets distinct vulnerabilities from the latest Scan of a Project */ async distinctSeverities(project: Project): Promise<ProjectDistinctSeverityDto[]> { const scan = await this.latestCompletedScan(project); if (scan) { return this.scanService.distinctSeverities(scan); } else { return []; } } async distinctUserIds(): Promise<any> { return this.db.createQueryBuilder('project').select('project.userId').addGroupBy('project.userId').getRawMany(); } /** * Gets distinct vulnerabilities from the latest Scan of a Project */ async distinctVulnerabilities(project: Project): Promise<ProjectDistinctVulnerabilityDto[]> { const scan = await this.latestCompletedScan(project); if (scan) { return this.scanService.distinctVulnerabilities(scan); } else { return []; } } async getprojectAttribution(project: Project): Promise<ProjectAttributionDto> { const projectAttribution = new ProjectAttributionDto(); const projectAttributionFound = await this.projectAttributionService.findOne({ where: { project: project }, }); if (projectAttributionFound) { projectAttribution.licenseText = projectAttributionFound.attribution; } else { projectAttribution.licenseText = 'Successful scan required for attribution'; } return projectAttribution; } getUsersProjectsQuery(userId: string): SelectQueryBuilder<Project> { return this.db.createQueryBuilder('project').where('project.userId IN (:...userId)', { userId }); } async gitUrlAuthForProject(project: Project) { const log = new Logger('gitUrlAuthForProject'); let gitUrl = project.gitUrl; log.log(`gitUrl: ${gitUrl}`); if (gitUrl) { const urlParts = url.parse(gitUrl); const config = await SystemConfiguration.defaultConfiguration(); let username = null; let password = null; // If it is a GutHub.com URL, add the Github credentials const isGitHubCom = urlParts.hostname.toLowerCase() === 'github.com'; if (isGitHubCom) { log.log(`isGitHubCom: ${isGitHubCom}`); if (config.githubComUsernameEnvVar && config.githubComPasswordEnvVar) { if (process.env[config.githubComUsernameEnvVar]) { username = process.env[config.githubComUsernameEnvVar]; log.log(`Setting username: process.env['${config.githubComUsernameEnvVar}']`); } if (process.env[config.githubComPasswordEnvVar]) { password = process.env[config.githubComPasswordEnvVar]; log.log(`Setting password: process.env['${config.githubComPasswordEnvVar}']`); } } } else { // If it is a GutHub Enterprise URL, add GHE credentials let isGitHubEnterprise = false; if (process.env[config.githubEnterpriseUrlEnvVar]) { const gheUrl = process.env[config.githubEnterpriseUrlEnvVar]; log.log(`gheUrl: ${gheUrl}`); if (gheUrl) { isGitHubEnterprise = urlParts.hostname.toLowerCase() === gheUrl.toLowerCase(); if (isGitHubEnterprise) { log.log(`isGitHubEnterprise: ${isGitHubEnterprise}`); } } } if (isGitHubEnterprise) { if (config.githubEnterpriseUsernameEnvVar && config.githubEnterprisePasswordEnvVar) { username = process.env[config.githubEnterpriseUsernameEnvVar]; password = process.env[config.githubEnterprisePasswordEnvVar]; log.log(`Setting username: process.env['${config.githubEnterpriseUsernameEnvVar}']`); log.log(`Setting password: process.env['${config.githubEnterprisePasswordEnvVar}']`); if (process.env[config.githubEnterpriseUsernameEnvVar]) { username = process.env[config.githubEnterpriseUsernameEnvVar]; log.log(`Setting username: process.env['${config.githubEnterpriseUsernameEnvVar}']`); } if (process.env[config.githubEnterprisePasswordEnvVar]) { password = process.env[config.githubEnterprisePasswordEnvVar]; log.log(`Setting password: process.env['${config.githubEnterprisePasswordEnvVar}']`); } } } } if (username && password) { urlParts.auth = `${username}:${password}`; gitUrl = url.format(urlParts); urlParts.auth = `${username}:********`; log.log(`gitUrl: ${url.format(urlParts)}`); } } return gitUrl; } async highestLicenseStatus(project: Project): Promise<ProjectScanStatusType> { const scan = await this.latestCompletedScan(project); if (scan) { const licenseScan = await this.scanService.latestCompletedLicenseScan(scan); return this.scanService.highestLicenseStatus(licenseScan, project); } else { if (project.globalLicenseException) { return ProjectScanStatusTypeService.Green(); } else if ((await this.bomManualLicenseService.manualLicenseCount(project)) > 0) { // Must account for the condition when there exists a manual license, but no scans return this.scanService.highestLicenseStatus(null, project); } else { return ProjectScanStatusTypeService.Unknown(); } } } async highestSecurityStatus(project: Project): Promise<ProjectScanStatusType> { const scan = await this.latestCompletedScan(project); if (scan) { return this.scanService.highestSecurityStatus(scan, project); } else { if (project.globalSecurityException) { return ProjectScanStatusTypeService.Green(); } else { return ProjectScanStatusTypeService.Unknown(); } } } /** * Gets the latest completed Scan of a Project */ async latestCompletedScan(project: Project): Promise<Scan> { return await Scan.createQueryBuilder('scan') .leftJoin('scan.project', 'project') .where('project.id = :id and scan.completed_at is not null', { id: project.id, }) .orderBy('scan.completed_at', 'DESC') .limit(1) .getOne(); } async rawQuery<T = any[]>(query: string, parameters: object = {}): Promise<T> { const conn = this.db.manager.connection; const [escapedQuery, escapedParams] = conn.driver.escapeQueryWithParameters(query, parameters, {}); return conn.query(escapedQuery, escapedParams); } async getProjectsMany( parsed: ParsedRequestParams, options: CrudRequestOptions, userId: string[], ): Promise<Project[]> { let builder = await this.createBuilder(parsed, options); if (userId && parsed.filter.length) { builder = builder.andWhere('Project.userId IN (:...userId)', { userId }); } else if (userId) { builder = builder.where('Project.userId IN (:...userId)', { userId }); } const log = new Logger('getProjectsMany'); const projects = await builder.getMany(); if ( !projects.length || (parsed.fields.length && !parsed.fields.includes('latestSecurityStatus') && !parsed.fields.includes('latestLicenseStatus')) ) { return projects; } const projectArray = projects.map((project) => project.id); const query = ` select p.id, max(psst.sort_order) as maxSecurity, case when max(psst.sort_order) = 3 then 'Red' when max(psst.sort_order) = 2 then 'Yellow' when max(psst.sort_order) = 1 then 'Green' else 'Green' end as latestSecurityStatus, null as latestLicenseStatus from project p left join scan s2 on p.id = s2."projectId" and s2.id = ( select Max(s3.id) from scan s3 where s3."projectId" = p.id and s3.completed_at is not null) left join security_scan_result ssr on ssr."scanId" = s2.id left join security_scan_result_item ssri on ssr.id = ssri."securityScanId" and not exists ( select id from bom_security_exception bse where s2."projectId" = bse."projectId" and ssri."path" = bse."securityItemPath") left join project_scan_status_type psst on ssri.project_scan_status_type_code = psst.code where s2.completed_at is not null and p.id in (:...projectIds) group by p.id union select p.id, max(psst.sort_order) as maxSecurity, null as latestSecurityStatus, case when max(psst.sort_order) = 3 then 'Red' when max(psst.sort_order) = 2 then 'Yellow' when max(psst.sort_order) = 1 then 'Green' else 'Unknown' end as latestLicenseStatus from project p left join scan s2 on p.id = s2."projectId" and s2.id = ( select Max(s3.id) from scan s3 where s3."projectId" = p.id and s3.completed_at is not null) left join license_scan_result lsr on lsr."scanId" = s2.id left join license_scan_result_item lsri on lsr.id = lsri."licenseScanId" and not exists ( select id from bom_license_exception ble where s2."projectId" = ble."projectId" and lsri."displayIdentifier" = ble."licenseItemPath") left join project_scan_status_type psst on lsri.project_scan_status_type_code = psst.code where s2.completed_at is not null and p.id in (:...projectIds) group by p.id`; const latestStatus = await this.rawQuery<any>(query, { projectIds: projectArray }); const licenseExceptionQuery = ` select "projectId" as id, max(psst.sort_order) as maxSecurity, null as latestSecurityStatus, case when max(psst.sort_order) = 3 then 'Red' when max(psst.sort_order) = 2 then 'Yellow' when max(psst.sort_order) = 1 then 'Green' else 'Unknown' end as latestLicenseStatus from bom_license_exception ble left join project_scan_status_type psst on ble.project_scan_status_type_code = psst.code where "projectId" in (:...projectIds) group by "projectId"`; const licenseExceptions = await this.rawQuery<any>(licenseExceptionQuery, { projectIds: projectArray }); const licenseManualQuery = `select bml."projectId" as id , max(psst.sort_order) as maxSecurity, null as latestSecurityStatus, case when max(psst.sort_order) = 3 then 'Red' when max(psst.sort_order) = 2 then 'Yellow' when max(psst.sort_order) = 1 then 'Green' else 'Green' end as latestLicenseStatus from bom_manual_license bml left join project p2 on p2.id = bml."projectId" left join license l2 on bml."licenseId" = l2.id left join license_status_deployment_type lsdt on lsdt.license_code = l2.code and lsdt.deployment_type_code = p2.deployment_type_code left join project_scan_status_type psst on lsdt.project_scan_status_type_code = psst.code where bml."projectId" in (:...projectIds) group by "projectId"`; const licenseManual = await this.rawQuery<any>(licenseManualQuery, { projectIds: projectArray }); projects.map(function (project) { var latest = latestStatus.find((stat) => stat.id === project.id && !stat.latestlicensestatus); if (!parsed.fields.length || parsed.fields.includes('latestSecurityStatus')) { if (latest?.latestsecuritystatus) { project.latestSecurityStatus = latest.latestsecuritystatus; } else { if (project.globalSecurityException) { project.latestSecurityStatus = 'Green'; } else { project.latestSecurityStatus = 'Unknown'; } } } var latest = latestStatus.find((stat) => stat.id === project.id && !stat.latestsecuritystatus); if (!parsed.fields.length || parsed.fields.includes('latestLicenseStatus')) { if (latest?.latestlicensestatus) { var latestexception = licenseExceptions.find((exception) => exception.id === project.id); if (latestexception) { project.latestLicenseStatus = latest.maxsecurity < latestexception.maxsecurity ? latestexception.latestlicensestatus : latest.latestlicensestatus; } else { project.latestLicenseStatus = latest.latestlicensestatus; } var latestmanual = licenseManual.find((manual) => manual.id === project.id); if (latestmanual) { project.latestLicenseStatus = latest.maxsecurity < latestmanual.maxsecurity ? latestmanual.latestlicensestatus : latest.latestlicensestatus; } else { project.latestLicenseStatus = latest.latestlicensestatus; } } else { if (project.globalLicenseException) { project.latestLicenseStatus = 'Green'; } else { project.latestLicenseStatus = 'Unknown'; } } } }); return projects; } async uniqueBomObligations( projectId: number, page: number, pageSize: number, ): Promise<GetManyDefaultResponse<ObligationSearchDto>> { const query = ` select * from obligation where code in ( select loo."obligationCode" from license_obligations_obligation loo where loo."licenseCode" in ( select l.code from scan s, license_scan_result lsr, license_scan_result_item lsri, license l where s."projectId" = $1 and lsr."scanId" = s.id and lsr.id = lsri."licenseScanId" and l.id = lsri."licenseId" union select l.code from bom_manual_license bomml, license l where bomml."projectId" = $1 and l.id = bomml."licenseId" group by l.code) group by loo."obligationCode")`; return await PaginateRawQuery(this.db.manager, query, [projectId], page, pageSize, (record) => ({ id: record.id, code: record.code, name: record.name, desc: record.desc, })); } }
the_stack
import React, { useCallback, useEffect, useRef, useState } from 'react' import { ConditionalKeys } from 'type-fest' import createDeferred, { Deferred } from '../../common/async/deferred' import shallowEquals from '../../common/shallow-equals' interface FormHook<ModelType> { /** * Event handler that should be attached to the `form` element's onSubmit prop. This can also be * called directly if you want to start a form submission because of some other event. */ onSubmit: (event?: React.FormEvent) => void /** * Returns a list of props that bind a checkbox or checkbox-like element to the form wrapper, * such that validations can run on it when it changes and error messages will be displayed. * * Example: * * ``` * <CheckBox * {...bindCheckable('myCoolValue')} * label='Cool value' * /> * ``` */ bindCheckable: <K extends OptionalConditionalKeys<ModelType, boolean>>( name: K, ) => { name: K onChange: (event: React.ChangeEvent<HTMLInputElement>) => void checked: boolean errorText: string | undefined } /** * Returns a list of props that bind a custom (non-HTMLInputElement-based) element to the form * wrapper, such that validations can run on it when it changes and error messages will be * displayed. * * Example: * * ``` * <NumberTextField * {...bindCustom('myCustomValue')} * label={'Custom value'} * /> * ``` */ bindCustom: <K extends keyof ModelType>( name: K, ) => { name: K onChange: (newValue: ModelType[K]) => void // TODO(tec27): Probably this should be encapsulated in the ModelType instead of doing this // conversion? value: ModelType[K] | null errorText: string | undefined } /** * Returns a list of props to bind an input (with a string value) element to the form wrapper, * such that validations can run on it when it changes and error messages will be displayed. * * Example: * * ``` * <TextField * {...bindInput('myInput')} * label={'Input something'} * /> * ``` */ bindInput: <K extends OptionalConditionalKeys<ModelType, string>>( name: K, ) => { name: K onChange: (event: React.ChangeEvent<HTMLInputElement>) => void value: string errorText: string | undefined } /** * Returns the current value for form input `name` in the model. */ getInputValue: <K extends keyof ModelType>(name: K) => ModelType[K] /** * Sets the current value for form input `name` in the model. */ setInputValue: <K extends keyof ModelType>(name: K, value: ModelType[K]) => void /** * Sets the current error for form input `name` in the model. Can be `undefined` to clear * existing errors. */ setInputError: (name: keyof ModelType, errorMsg: string | undefined) => void } export type SyncValidator<ValueType, ModelType> = ( value: Readonly<ValueType>, model: Readonly<ModelType>, dirty: ReadonlyMap<keyof ModelType, boolean>, ) => string | undefined export type AsyncValidator<ValueType, ModelType> = ( value: Readonly<ValueType>, model: Readonly<ModelType>, dirty: ReadonlyMap<keyof ModelType, boolean>, ) => Promise<string | undefined> export type Validator<ValueType, ModelType> = | SyncValidator<ValueType, ModelType> | AsyncValidator<ValueType, ModelType> export type ValidatorMap<ModelType> = Partial<{ [K in keyof ModelType]: Validator<ModelType[K], ModelType> }> /** * React hook that provides methods for binding form inputs to update an underlying model and run * sync or async validations. * * @param model The initial values for the form. This object will not be re-checked after initial * render (similar semantics to `useState`). * @param validations A mapping of name -> a function to validate a value for that form input. Any * missing names will be assumed to be valid at all times. * @param onSubmit A callback for when the form has been submitted and is free of validation errors */ export function useForm<ModelType>( model: Readonly<ModelType>, validations: Readonly<ValidatorMap<ModelType>>, callbacks: { onSubmit?: (model: Readonly<ModelType>) => void onChange?: (model: Readonly<ModelType>) => void } = {}, ): FormHook<ModelType> { const [modelValue, setModelValue] = useState(model) const stateModelRef = useRef(modelValue) const callbacksRef = useRef(callbacks) const [validationErrors, setValidationErrors] = useState< Partial<Record<keyof ModelType, string>> >(Object.create(null)) // NOTE(tec27): This always just gets updated with the latest state value, so that we can check // it when needed (e.g. when submitting the form, after async validations come back) const validationErrorsRef = useRef(validationErrors) const dirtyFieldsRef = useRef(new Map<keyof ModelType, boolean>()) const validationPromisesRef = useRef(new Map<keyof ModelType, Promise<string | undefined>>()) const notifyValidationRef = useRef<Array<Deferred<void>>>([]) const validate = useCallback( (name: keyof ModelType) => { if (!validations.hasOwnProperty(name)) { return } const resultPromise = Promise.resolve( validations[name]!( stateModelRef.current[name], stateModelRef.current, dirtyFieldsRef.current, ), ) validationPromisesRef.current.set(name, resultPromise) resultPromise.then(errorMsg => { if (validationPromisesRef.current.get(name) !== resultPromise) { // A newer validation is running on this input, ignore this result return } validationPromisesRef.current.delete(name) setValidationErrors(validationErrors => ({ ...validationErrors, [name]: errorMsg, })) }) // Wake up all the things waiting for validations to complete to tell them there is a new // validation promise for (const deferred of notifyValidationRef.current) { deferred.resolve() } notifyValidationRef.current.length = 0 }, [validations], ) const handleSubmit = useCallback( (event?: React.FormEvent) => { // Don't actually submit the form over HTTP event?.preventDefault() // Run validations against everything that's not dirty to double-check their validity. for (const name of Object.keys(validations)) { if (!dirtyFieldsRef.current.get(name as keyof ModelType)) { validate(name as keyof ModelType) } } const checkValidations = () => { if (Object.values(validationErrorsRef.current).some(v => !!v)) { // Form isn't valid, don't submit // TODO(tec27): focus first invalid field? return } if (!validationPromisesRef.current.size) { // Form is valid and we're not waiting on any validations, submit! if (callbacksRef.current.onSubmit) { callbacksRef.current.onSubmit(stateModelRef.current) } } else { // Wait for any validations to finish, or for a new validation request to occur. When // either of those things happen, we re-check the validations const interrupt = createDeferred<void>() notifyValidationRef.current.push(interrupt) Promise.race( Array.from<Promise<any>>(validationPromisesRef.current.values()).concat(interrupt), ).finally(checkValidations) } } checkValidations() }, [validate, validations], ) validationErrorsRef.current = validationErrors callbacksRef.current = callbacks const lastModelValue = stateModelRef.current stateModelRef.current = modelValue useEffect(() => { if (!shallowEquals(lastModelValue, modelValue)) { for (const [name, dirty] of dirtyFieldsRef.current.entries()) { // TODO(tec27): Ideally this would only re-validate things that changed in the model, // but we can't really do that because the full understanding of dependencies aren't // noted (e.g. if you validate that a field matches another one, you need to re-run // that validation if *either* field changes). if (dirty) { validate(name) } } if (callbacksRef.current.onChange) { callbacksRef.current.onChange(modelValue) } } }, [lastModelValue, modelValue, validate]) useEffect(() => { return () => { // Ensure that validations do nothing once unmounted // Disabling lint because it's fine if the value of this ref has changed at this point // eslint-disable-next-line react-hooks/exhaustive-deps validationPromisesRef.current.clear() callbacksRef.current = {} } }, []) // TODO(tec27): Impelement a way to reset the form (can probably be done similarly to // useRefreshToken?) const formGetterSetters = useFormGetterSetters({ stateModelRef, dirtyFieldsRef, validationErrorsRef, setModelValue, setValidationErrors, }) return { ...formGetterSetters, onSubmit: handleSubmit, } } type StateSetter<T> = React.Dispatch<React.SetStateAction<T>> type OptionalConditionalKeys<T, MatchType> = ConditionalKeys<T, MatchType | undefined> type CustomChangeHandler = (newValue: any) => void function useFormGetterSetters<ModelType>({ stateModelRef, dirtyFieldsRef, validationErrorsRef, setModelValue, setValidationErrors, }: { stateModelRef: React.MutableRefObject<Readonly<ModelType>> dirtyFieldsRef: React.MutableRefObject<Map<keyof ModelType, boolean>> validationErrorsRef: React.MutableRefObject<Partial<Record<keyof ModelType, string>>> setModelValue: StateSetter<Readonly<ModelType>> setValidationErrors: StateSetter<Partial<Record<keyof ModelType, string>>> }) { const customChangeHandlersRef = useRef(new Map<keyof ModelType, CustomChangeHandler>()) const getInputValue = useCallback( <K extends keyof ModelType>(name: K) => stateModelRef.current[name], [stateModelRef], ) const setInputValue = useCallback( <K extends keyof ModelType>(name: K, value: ModelType[K]) => { dirtyFieldsRef.current.set(name, true) setModelValue(model => ({ ...model, [name]: value, })) }, [dirtyFieldsRef, setModelValue], ) const setInputError = useCallback( (name: keyof ModelType, errorMsg?: string) => { setValidationErrors(validationErrors => ({ ...validationErrors, [name]: errorMsg, })) }, [setValidationErrors], ) const onInputChange = useCallback( (event: React.ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target setInputValue(name as keyof ModelType, value as any) }, [setInputValue], ) const onCheckableChange = useCallback( (event: React.ChangeEvent<HTMLInputElement>) => { const { name, checked } = event.target setInputValue(name as keyof ModelType, checked as any) }, [setInputValue], ) const onCustomChange = useCallback( <K extends keyof ModelType>(name: K, newValue: ModelType[K]) => { setInputValue(name, newValue) }, [setInputValue], ) const bindInput = useCallback( <K extends OptionalConditionalKeys<ModelType, string>>(name: K) => { // NOTE(tec27): The K param here guarantees this will be a string but TS can't quite convince // itself of that, so we have to help it along const value = (stateModelRef.current[name] ?? '') as string return { name, onChange: onInputChange, value, errorText: validationErrorsRef.current[name], } }, [onInputChange, stateModelRef, validationErrorsRef], ) const bindCheckable = useCallback( <K extends OptionalConditionalKeys<ModelType, boolean>>(name: K) => { return { name, onChange: onCheckableChange, checked: !!stateModelRef.current[name], errorText: validationErrorsRef.current[name], } }, [onCheckableChange, stateModelRef, validationErrorsRef], ) const bindCustom = useCallback( <K extends keyof ModelType>(name: K) => { if (!customChangeHandlersRef.current.has(name)) { customChangeHandlersRef.current.set(name, (newValue: ModelType[K]) => onCustomChange(name, newValue), ) } return { name, onChange: customChangeHandlersRef.current.get(name)!, value: stateModelRef.current[name], errorText: validationErrorsRef.current[name], } }, [onCustomChange, stateModelRef, validationErrorsRef], ) return { getInputValue, setInputValue, setInputError, bindInput, bindCheckable, bindCustom, } }
the_stack
import { CMIBoolean, CMIBlank, CMIString255, CMIIdentifier, CMIDecimal, CMITimeSpan, CMIString4096, CMIInteger, CMISInteger, CMITime, CMIFeedback, } from './CMIDataTypes'; import { CMIElementComments, CMIElementCommentsFromLMS, CMIElementCoreChildren, CMIElementCoreCredit, CMIElementCoreEntry, CMIElementCoreExit, CMIElementCoreLessonLocation, CMIElementCoreLessonMode, CMIElementCoreLessonStatus, CMIElementCoreScoreChildren, CMIElementCoreScoreMax, CMIElementCoreScoreMin, CMIElementCoreScoreRaw, CMIElementCoreSessionTime, CMIElementCoreStudentId, CMIElementCoreStudentName, CMIElementCoreTotalTime, CMIElementInteractionsChildren, CMIElementInteractionsCount, CMIElementInteractionsNCorrectResponsesCount, CMIElementInteractionsNCorrectResponsesNPattern, CMIElementInteractionsNID, CMIElementInteractionsNLatency, CMIElementInteractionsNObjectivesCount, CMIElementInteractionsNResult, CMIElementInteractionsNStudentResponse, CMIElementInteractionsNTime, CMIElementInteractionsNType, CMIElementInteractionsNWeighting, CMIElementLaunchData, CMIElementObjectivesChildren, CMIElementObjectivesCount, CMIElementObjectivesNID, CMIElementObjectivesNScoreChildren, CMIElementObjectivesNScoreMax, CMIElementObjectivesNScoreMin, CMIElementObjectivesNScoreRaw, CMIElementObjectivesNStatus, CMIElementStudentDataChildren, CMIElementStudentDataMasteryScore, CMIElementStudentDataMaxTimeAllowed, CMIElementStudentDataTimeLimitAction, CMIElementStudentPreferenceAudio, CMIElementStudentPreferenceChildren, CMIElementStudentPreferenceLanguage, CMIElementStudentPreferenceSpeed, CMIElementStudentPreferenceText, CMIElementSuspendData, CMIElementVersion, } from './CMIElement'; import { CMIErrorCode } from './CMIErrorCode'; import { CMIVocabularyCredit, CMIVocabularyEntry, CMIVocabularyExit, CMIVocabularyInteraction, CMIVocabularyMode, CMIVocabularyResult, CMIVocabularyStatus, CMIVocabularyTimeLimitAction, } from './CMIVocabulary'; export * from './CMIDataTypes'; export * from './CMIElement'; export * from './CMIErrorCode'; export * from './CMIVocabulary'; /** * The Sharable Content Object Reference Model (SCORM) Version 1.2 Run-Time Environment */ export interface SCORM12 { // Execution State /** * Begins a communication session with the LMS. * @param param The “” parameter is required by all SCORM methods that don’t accept any other arguments. */ LMSInitialize(param: CMIBlank): CMIBoolean; /** * Ends a communication session with the LMS. * @param param The “” parameter is required by all SCORM methods that don’t accept any other arguments. */ LMSFinish(param: CMIBlank): CMIBoolean; // Data Transfer /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreChildren): CMIString255; /** * Unique alpha-numeric code / identifier that refers to a single user of the LMS system. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreStudentId): CMIIdentifier; /** * Normally, the official name used for the student on the course roster. A complete name, not just a first name. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreStudentName): CMIString255; /** * This corresponds to the SCO exit point passed to the LMS system the last time the student experienced the SCO. This provides one mechanism to let the student return to a SCO at the same place * he left it earlier. In other words, this element can identify the student's exit point and that exit point can be used by the SCO as an entry point the next time the student runs the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreLessonLocation): CMIString255; /** * Indicates whether the student is being credited by the LMS system based on performance (pass/fail and score) in this SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreCredit): CMIVocabularyCredit; /** * This is the current student status as determined by the LMS system. Six status values are possible. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreLessonStatus): CMIVocabularyStatus; /** * Indication of whether the student has been in the SCO before. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreEntry): CMIVocabularyEntry; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreScoreChildren): CMIString255; /** * Indication of the performance of the student during his last attempt on the SCO. This score may be determined and calculated in any manner that makes sense to the SCO designer. For instance, * it could reflect the percentage of objectives complete, it could be the raw score on a multiple choice test, or it could indicate the number of correct first responses to embedded questions in * a SCO. * * The cmi.core.score.raw must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreScoreRaw): CMIDecimal | CMIBlank; /** * The maximum score or total number that the student could have achieved. * * The cmi.core.score.max must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreScoreMax): CMIDecimal | CMIBlank; /** * The minimum score that the student could have achieved. * * The cmi.core.score.min must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreScoreMin): CMIDecimal | CMIBlank; /** * Accumulated time of all the student's sessions in the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreTotalTime): CMITimeSpan; /** * Identifies the SCO behavior desired after launch. Many SCOs have a single "behavior". Some SCOs, however, can present different amounts of information, or present information in different * sequences, or present information reflecting different training philosophies based on an instructor's or designer's decisions. Designers may enable SCOs to behave in a virtually unlimited * number of ways. This standard supports the communication of three parameters that may result in different SCO behaviors. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCoreLessonMode): CMIVocabularyMode; /** * Unique information generated by the SCO during previous uses that is needed for the current use. This unique information is applicable to a launching SCO. Normally this is the element used * by the SCO for restart information. This is normally data that is created by the SCO and stored by the LMS to pass back to the SCO the next time the SCO is run. * * The LMS must set aside a space for this group for each SCO for each student. It stores this data and returns it to the SCO when it is run again. The LMS shall retain this data as long as the * student is in the course. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementSuspendData): CMIString4096; /** * Unique information generated at the SCO's creation that is needed for every use. Without this information, a SCO may not execute. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementLaunchData): CMIString4096; /** * Freeform feedback from the SCO. For example, the student may have the option of leaving comments at any point in the SCO, or they may be asked for comments at the end of the SCO. The comment * may also have an indication of where or when in the SCO it was created. A location may be tagged and embedded in the comment. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementComments): CMIString4096; /** * This element represents comments that would come from the LMS. An example of how this might be used is in the form of instructor comments. These types of comments are directed at the student * that the SCO may present to the student when appropriate. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementCommentsFromLMS): CMIString4096; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesChildren): CMIString255; /** * The _count keyword is used to determine the current number of records in the cmi.objectives list. The total number of entries is returned. If the SCO does not know the count of the * cmi.objectives records, it can begin the current student count with 0. This would overwrite any information about objectives currently stored in the first index position. Overwriting or * appending is a decision that is made by the SCO author when he/she creates the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesCount): CMIInteger; /** * An internally, developer defined, SCO specific identifier for an objective. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNID): CMIIdentifier; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNScoreChildren): CMIString255; /** * Numerical representation of student performance after each attempt on the objective. May be unprocessed raw score. * * The cmi.objectives.n.score.raw must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNScoreRaw): CMIDecimal | CMIBlank; /** * The maximum score or total number that the student could have achieved on the objective. * * The cmi.objectives.n.score.max must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNScoreMax): CMIDecimal | CMIBlank; /** * The minimum score that the student could have achieved on the objective. * * The cmi.objectives.n.score.min must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNScoreMin): CMIDecimal | CMIBlank; /** * The status of the SCO's objective obtained by the student after each attempt to master the SCO's objective. Only 6 possible vocabulary values: passed, completed, failed, incomplete, not * attempted or browsed. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementObjectivesNStatus): CMIVocabularyStatus; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentDataChildren): CMIString255; /** * The passing score, as determined outside the SCO. When the SCO score is greater than or equal to the mastery score, the student is considered to have passed, or mastered the content. In some * cases, the SCO does not know what this passing score is, because it is determined by the LMS system. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentDataMasteryScore): CMIDecimal; /** * The amount of time the student is allowed to have in the current attempt on the SCO. See time_limit_action for the SCO's expected response to exceeding the limit. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentDataMaxTimeAllowed): CMITimeSpan; /** * Tells the SCO what to do when the max_time_allowed is exceeded. There iare two arguments for this element: * * - What the SCO should do - exit or continue * - What the student should see - message or no message */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentDataTimeLimitAction): CMIVocabularyTimeLimitAction; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentPreferenceChildren): CMIString255; /** * Audio may be turned off, or its volume controlled. The element indicates whether the audio is turned off, or on. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentPreferenceAudio): CMISInteger; /** * For SCOs with multi-lingual capability, this element should be used to identify in what language the information should be delivered. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentPreferenceLanguage): CMIString255; /** * SCOs may sometimes be difficult to understand because of the pace. This element controls the pace of the content delivery. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentPreferenceSpeed): CMISInteger; /** * In a SCO designed for audio, it may be possible to turn off the audio, and view the audio content in a text window. Or it may be possible to leave the audio on, and request that the text be * presented simultaneously with the audio. Or it may be possible to make the text disappear so that only the audio and the screen graphics are available. This element defines whether the audio * text appears in the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementStudentPreferenceText): CMISInteger; /** * The _children keyword is used to determine all of the elements in the core category that are supported by the LMS. If an element has no children, but is supported, an empty string is returned. * If an element is not supported, an empty string is returned. A subsequent request for last error can verify that the element is not supported. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementInteractionsChildren): CMIString255; /** * The _count keyword is used to determine the current number of records in the cmi.interactions list. The total number of entries is returned. If the SCO does not know the count of the * cmi.interactions records, it can begin the current student count with 0. This would overwrite any information about interactions currently stored in the first index position. Overwriting or * appending is a decision that is made by the SCO author when he/she creates the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementInteractionsCount): CMIInteger; /** * The _count keyword is used to determine the current number of records in the cmi.interactions objective id list. The total number of entries is returned. If the SCO does not know the count of * the cmi.interactions.n.objecives records, it can begin the current student count with 0. This would overwrite any information about objective ids currently stored in the first index position. * Overwriting or appending is a decision that is made by the SCO author when he/she creates the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementInteractionsNObjectivesCount): CMIInteger; /** * The _count keyword is used to determine the current number of records in the cmi.interactions correct responses list. The total number of entries is returned. If the SCO does not know the * count of the cmi.interactions.n.correct_responses records, it can begin the current student count with 0. This would overwrite any information about correct responses currently stored in the * first index position. Overwriting or appending is a decision that is made by the SCO author when he/she creates the SCO. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementInteractionsNCorrectResponsesCount): CMIInteger; /** * The _version keyword is used to determine the version of the data model supported by the LMS. */ // tslint:disable-next-line:unified-signatures LMSGetValue(element: CMIElementVersion): CMIString255; /** * This corresponds to the SCO exit point passed to the LMS system the last time the student experienced the SCO. This provides one mechanism to let the student return to a SCO at the same place * he left it earlier. In other words, this element can identify the student's exit point and that exit point can be used by the SCO as an entry point the next time the student runs the SCO. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreLessonLocation, value: CMIString255): CMIBoolean; /** * This is the current student status as determined by the LMS system. Six status values are possible. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreLessonStatus, value: CMIVocabularyStatus): CMIBoolean; /** * Indication of the performance of the student during his last attempt on the SCO. This score may be determined and calculated in any manner that makes sense to the SCO designer. For instance, * it could reflect the percentage of objectives complete, it could be the raw score on a multiple choice test, or it could indicate the number of correct first responses to embedded questions in * a SCO. * * The cmi.core.score.raw must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreScoreRaw, value: CMIDecimal | CMIBlank): CMIBoolean; /** * The maximum score or total number that the student could have achieved. * * The cmi.core.score.max must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreScoreMax, value: CMIDecimal | CMIBlank): CMIBoolean; /** * The minimum score that the student could have achieved. * * The cmi.core.score.min must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreScoreMin, value: CMIDecimal | CMIBlank): CMIBoolean; /** * An indication of how or why the student has left the SCO. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreExit, value: CMIVocabularyExit): CMIBoolean; /** * This is the amount of time in hours, minutes and seconds that the student has spent in the SCO at the time they leave it. That is, this represents the time from beginning of the session to the * end of a single use of the SCO. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementCoreSessionTime, value: CMITimeSpan): CMIBoolean; /** * Unique information generated by the SCO during previous uses that is needed for the current use. This unique information is applicable to a launching SCO. Normally this is the element used by * the SCO for restart information. This is normally data that is created by the SCO and stored by the LMS to pass back to the SCO the next time the SCO is run. * * The LMS must set aside a space for this group for each SCO for each student. It stores this data and returns it to the SCO when it is run again. The LMS shall retain this data as long as the * student is in the course. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementSuspendData, value: CMIString4096): CMIBoolean; /** * Freeform feedback from the SCO. For example, the student may have the option of leaving comments at any point in the SCO, or they may be asked for comments at the end of the SCO. The comment * may also have an indication of where or when in the SCO it was created. A location may be tagged and embedded in the comment. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementComments, value: CMIString4096): CMIBoolean; /** * An internally, developer defined, SCO specific identifier for an objective. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementObjectivesNID, value: CMIIdentifier): CMIBoolean; /** * Numerical representation of student performance after each attempt on the objective. May be unprocessed raw score. * * The cmi.objectives.n.score.raw must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementObjectivesNScoreRaw, value: CMIDecimal | CMIBlank): CMIBoolean; /** * The maximum score or total number that the student could have achieved on the objective. * * The cmi.objectives.n.score.max must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementObjectivesNScoreMax, value: CMIDecimal | CMIBlank): CMIBoolean; /** * The minimum score that the student could have achieved on the objective. * * The cmi.objectives.n.score.min must be a normalized value between 0 and 100. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementObjectivesNScoreMin, value: CMIDecimal | CMIBlank): CMIBoolean; /** * The status of the SCO's objective obtained by the student after each attempt to master the SCO's objective. Only 6 possible vocabulary values: passed, completed, failed, incomplete, not * attempted or browsed. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementObjectivesNStatus, value: CMIVocabularyStatus): CMIBoolean; /** * Audio may be turned off, or its volume controlled. The element indicates whether the audio is turned off, or on. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementStudentPreferenceAudio, value: CMISInteger): CMIBoolean; /** * For SCOs with multi-lingual capability, this element should be used to identify in what language the information should be delivered. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementStudentPreferenceLanguage, value: CMIString255): CMIBoolean; /** * SCOs may sometimes be difficult to understand because of the pace. This element controls the pace of the content delivery. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementStudentPreferenceSpeed, value: CMISInteger): CMIBoolean; /** * In a SCO designed for audio, it may be possible to turn off the audio, and view the audio content in a text window. Or it may be possible to leave the audio on, and request that the text be * presented simultaneously with the audio. Or it may be possible to make the text disappear so that only the audio and the screen graphics are available. This element defines whether the audio * text appears in the SCO. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementStudentPreferenceText, value: CMISInteger): CMIBoolean; /** * Unique identifier for an interaction. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNID, value: CMIIdentifier): CMIBoolean; /** * Identification of when the student interaction was completed. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNTime, value: CMITime): CMIBoolean; /** * Indication of which category of interaction is recorded. The type of interction determines how the interaction response should be interpreted. Eight possible question types are defined. They * are not meant to be limiting. There are other types of questions. However, if one of these eight types is used, these are the identifiers that match those types. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNType, value: CMIVocabularyInteraction): CMIBoolean; /** * Description of possible student responses to the interaction. There may be more than one correct response, and some responses may be more correct than others. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNCorrectResponsesNPattern, value: CMIFeedback): CMIBoolean; /** * Interactions vary in importance. The weighting is a factor which is used to identify the relative importance of one interaction compared to another. For instance, if the first interaction has * a weight of 15 and the second interaction has a weight of 25, then any combined score that reflects weighting would be more influenced by the second interaction. * * If all interactions are equal in importance, then each interaction has the same weight. * * A weight of 0 indicates that the interaction should not be counted in the weighted final score. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNWeighting, value: CMIDecimal): CMIBoolean; /** * Description of possible responses to the interaction. There may be more than one correct response, and some responses may be more correct than others. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNStudentResponse, value: CMIFeedback): CMIBoolean; /** * How the system judges the described response. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNResult, value: CMIVocabularyResult): CMIBoolean; /** * The time from the presentation of the stimulus to the completion of the measurable response. */ // tslint:disable-next-line:unified-signatures LMSSetValue(element: CMIElementInteractionsNLatency, value: CMITimeSpan): CMIBoolean; /** * Indicates to the LMS that all data should be persisted (not required). * @param param The “” parameter is required by all SCORM methods that don’t accept any other arguments. */ LMSCommit(param: CMIBlank): CMIBoolean; // State Management /** * Returns the error code that resulted from the last API call. */ LMSGetLastError(): CMIErrorCode; /** * Returns a short string describing the specified error code. * @param errorCode The CMIErrorCode data type is a three-digit number, represented by a string, that corresponds to one of the SCORM Run-Time error codes. */ LMSGetErrorString(errorCode: CMIErrorCode): string; /** * Returns detailed information about the last error that occurred. * @param errorCode The CMIErrorCode data type is a three-digit number, represented by a string, that corresponds to one of the SCORM Run-Time error codes. */ LMSGetDiagnostic(errorCode: CMIErrorCode): string; }
the_stack
import type * as P from 'xxscreeps/engine/db/storage/provider'; import type { KeyvalScript } from 'xxscreeps/engine/db/storage/script'; import type { MaybePromises } from './responder'; import fs from 'fs/promises'; import Fn from 'xxscreeps/utility/functional'; import { latin1ToBuffer, typedArrayToString } from 'xxscreeps/utility/string'; import { connect, makeClient, makeHost } from './responder'; import { SortedSet } from './sorted-set'; import { registerStorageProvider } from 'xxscreeps/engine/db/storage'; import { getOrSet } from 'xxscreeps/utility/utility'; import { BlobStorage } from './blob'; registerStorageProvider([ 'file', 'local' ], 'keyval', url => { const path = url.pathname.endsWith('/') ? url : new URL(`${url}/`); return connect(`${path}`, LocalKeyValClient, LocalKeyValHost, () => LocalKeyValResponder.create(path)); }); export class LocalKeyValResponder implements MaybePromises<P.KeyValProvider> { private readonly data = new Map<string, any>(); private readonly expires = new Set<string>(); private readonly scripts = new Map<string, (instance: LocalKeyValResponder, keys: string[], argv: P.Value[]) => any>(); constructor( private readonly url: URL | undefined, private readonly blob: BlobStorage, payload: string | undefined, ) { if (payload) { const map = JSON.parse(payload, (key, value) => { switch (value?.['#']) { case 'map': return new Map(Object.entries(value.$)); case 'set': return new Set(value.$); case 'zset': return new SortedSet(value.$); case 'uint8': return latin1ToBuffer(value.$); default: return value; } }); if (map instanceof Map) { this.data = map; } } } static async create(path: URL) { const [ blobEffect, blob ] = await BlobStorage.create(path); const [ url, payload ] = await async function() { if (path.protocol === 'file:') { const url = new URL('data.json', path); return [ url, await async function() { try { return await fs.readFile(new URL('data.json', path), 'utf8'); } catch {} }(), ] as const; } return []; }(); const host = new LocalKeyValResponder(url, blob, payload); return [ blobEffect, host ] as const; } copy(from: string, to: string, options?: P.Copy) { const value = this.data.get(from); if (value === undefined) { return this.blob.copy(from, to, options) as never; } else if (options?.if === 'nx' && this.data.has(to)) { return false; } else if (value instanceof Array) { this.data.set(to, [ ...value ]); } else if (value instanceof Map) { this.data.set(to, new Map(value.entries())); } else if (value instanceof Set) { this.data.set(to, new Set(value)); } else if (value instanceof SortedSet) { this.data.set(to, new SortedSet(value.entries())); } else { this.data.set(to, value); } return true; } del(key: string) { if (this.data.has(key)) { this.remove(key); return true; } else { return this.blob.del(key) as never; } } vdel(key: string) { this.del(key); } get(key: string, options?: P.AsBlob) { if (options?.blob) { return this.blob.get(key) as never; } else { const value = this.data.get(key); return value === undefined ? null : String(value); } } req(key: string, options?: P.AsBlob) { if (options?.blob) { return this.blob.req(key) as never; } else { const value = this.get(key); if (value === null) { throw new Error(`"${key}" does not exist`); } return value; } } set(key: string, value: P.Value, options?: P.Set): any { if (ArrayBuffer.isView(value)) { return this.blob.set(key, value, options) as never; } if ( options?.if === 'nx' ? this.data.has(key) : options?.if === 'xx' ? !this.data.has(key) : false ) { return null; } if (options?.px) { this.expires.add(key); } if (options?.get) { const current = this.data.get(key); this.data.set(key, value); return current === undefined ? null : `${current}`; } else { this.data.set(key, value); } } decr(key: string) { return this.incrBy(key, -1); } decrBy(key: string, delta: number) { return this.incrBy(key, -delta); } incr(key: string) { return this.incrBy(key, 1); } incrBy(key: string, delta: number) { const value = delta + (() => { const value = this.data.get(key); if (typeof value === 'number') { return value; } else if (value === undefined) { return 0; } else { const number = +value; if (Number.isNaN(number) || `${number}` !== value) { throw new Error(`"${key}" = ${value} is not an integer or out of range`); } return number; } })(); this.data.set(key, value); return value; } hget(key: string, field: string) { const map: Map<string, string> | undefined = this.data.get(key); return map?.get(field) ?? null; } hgetall(key: string) { const map: Map<string, string> | undefined = this.data.get(key); return map ? Fn.fromEntries(map.entries()) : {}; } hincrBy(key: string, field: string, value: number) { const map: Map<string, any> = getOrSet(this.data, key, () => new Map); const result = (Number(map.get(field)) || 0) + value; map.set(field, result); return result; } hmget(key: string, fields: Iterable<string>) { const map: Map<string, string | Readonly<Uint8Array>> | undefined = this.data.get(key); return Fn.fromEntries(Fn.map(fields, field => [ field, map?.get(field) ?? null ])) as never; } hset(key: string, field: string, value: P.Value, options?: P.HSet) { const map: Map<string, any> = getOrSet(this.data, key, () => new Map); const has = map.has(field); if (options?.if === 'nx' && has) { return false; } else { map.set(field, value); return !has; } } hmset(key: string, fields: Iterable<readonly [ string, P.Value ]> | Record<string, P.Value>) { const map: Map<string, any> = getOrSet(this.data, key, () => new Map); const iterable = Symbol.iterator in fields ? fields as Iterable<[ string, P.Value ]> : Object.entries(fields); for (const [ field, value ] of iterable) { map.set(field, value); } } lpop(key: string) { const list: string[] | undefined = this.data.get(key); if (!list) { return null; } if (list.length === 1) { this.remove(key); return list[0]; } else { return list.shift()!; } } lrange(key: string, start: number, stop: number) { const list: string[] | undefined = this.data.get(key); if (!list) { return []; } return list.slice( start >= 0 ? start : Math.max(0, list.length + start), stop >= 0 ? stop + 1 : Math.max(0, list.length + stop + 1), ); } rpush(key: string, elements: P.Value[]) { const list: string[] | undefined = this.data.get(key); const strings = Fn.map(elements, element => element) as string[]; if (list) { list.push(...strings); return list.length; } else { this.data.set(key, [ ...strings ]); return elements.length; } } sadd(key: string, members: string[]) { const set: Set<string> | undefined = this.data.get(key); if (set) { const { size } = set; members.forEach(value => set.add(value)); return set.size - size; } else if (members.length) { this.data.set(key, new Set(members)); return members.length; } else { return 0; } } scard(key: string) { const set: Set<string> | undefined = this.data.get(key); return set ? set.size : 0; } sdiff(key: string, keys: string[]) { const set: Set<string> | undefined = this.data.get(key); if (set) { const sets: (Set<string> | undefined)[] = keys.map(key => this.data.get(key)); return [ ...Fn.reject(set, member => sets.some(set => set?.has(member))) ]; } else { return []; } } sinter(key: string, keys: string[]) { const sets = [ ...Fn.filter(Fn.map( Fn.concat([ key ], keys), (key): Set<string> | undefined => this.data.get(key))) ]; sets.sort((left, right) => left.size - right.size); const first = sets.shift(); if (sets.length > 0) { return [ ...Fn.filter(first!, member => sets.every(set => set.has(member))) ]; } else { return []; } } sismember(key: string, member: string) { const set: Set<string> | undefined = this.data.get(key); return set?.has(member) ?? false; } smismember(key: string, members: string[]) { const set: Set<string> | undefined = this.data.get(key); if (set) { return members.map(member => set.has(member)); } else { return members.map(() => false); } } smembers(key: string) { const set: Set<string> | undefined = this.data.get(key); return set ? [ ...set ] : []; } spop(key: string) { const set: Set<string> | undefined = this.data.get(key); if (set) { const { value } = set.values().next(); if (set.size === 1) { this.remove(key); } else { set.delete(value); } return value as string; } return null; } srem(key: string, members: string[]) { const set = this.data.get(key); if (set) { const { size } = set; members.forEach(value => set.delete(value)); const result = size - set.size; if (result === size) { this.remove(key); } return result; } else { return 0; } } sunionStore(key: string, keys: string[]) { const sets = [ ...Fn.filter(Fn.map(keys, (key): Set<string> => this.data.get(key))) ]; const out = new Set(Fn.concat(sets)); this.data.set(key, out); return out.size; } zadd(key: string, members: [ number, string ][], options?: P.ZAdd): any { const set = getOrSet<string, SortedSet>(this.data, key, () => new SortedSet); try { const range = function() { switch (options?.if) { case 'nx': return Fn.reject(members, member => set.has(member[1])); case 'xx': return Fn.filter(members, member => set.has(member[1])); default: return members; } }(); if (options?.incr) { if (members.length > 1) { throw new Error('ZADD with INCR option cannot be used with multiple elements'); } const { head } = Fn.shift(range); if (!head) { return null; } const score = set.score(head[1]); if (score === undefined) { return null; } else { const result = score + head[0]; set.add(head[1], result); return result; } } return set.insert(range, (left, right) => right); } finally { if (set.size === 0) { this.data.delete(key); } } } zcard(key: string) { const set: SortedSet | undefined = this.data.get(key); return set ? set.size : 0; } zincrBy(key: string, delta: number, member: string) { const set = getOrSet<string, SortedSet>(this.data, key, () => new SortedSet); const score = (set.score(member) ?? 0) + delta; set.add(member, score); return score; } zinterStore(key: string, keys: string[], options?: P.ZAggregate) { // Fetch sets first because you can use this command to store a set back into itself const sets = [ ...Fn.filter(Fn.map(keys, (key): SortedSet => this.data.get(key))) ]; const out = function() { const smallest = Fn.minimum(sets, (left, right) => left.size - right.size); if (!smallest) { return new SortedSet; } // Generate intersection const weights = options?.weights ?? [ ...Fn.map(sets, () => 1) ]; return new SortedSet(function *(): Iterable<[ number, string ]> { loop: for (const member of smallest.values()) { let nextScore = 0; for (let ii = 0; ii < sets.length; ++ii) { const score = sets[ii].score(member); if (score === undefined) { continue loop; } nextScore += score * weights[ii]; } yield [ nextScore, member ]; } }()); }(); // Save result if (out.size > 0) { this.data.set(key, out); } else { this.data.delete(key); } return out.size; } zmscore(key: string, members: string[]) { const set: SortedSet | undefined = this.data.get(key); if (set) { return members.map(member => set.score(member) ?? null); } else { return members.map(() => null); } } zrange(key: string, min: number | string, max: number | string, options?: P.ZRange): any { const set: SortedSet | undefined = this.data.get(key); if (set) { const allMatching = function() { switch (options?.by) { case 'lex': { const parse = (value: string): [ string, boolean ] => { if (value === '-') { return [ '', true ]; } else if (value === '+') { return [ '\uffff', true ]; } else if (value.startsWith('(')) { return [ value.substr(1), false ]; } else if (value.startsWith('[')) { return [ value.substr(1), true ]; } else { throw new Error(`Invalid range: ${value}`); } }; const [ minVal, minInc ] = parse(min as string); const [ maxVal, maxInc ] = parse(max as string); return [ ...set.entriesByLex(minInc, minVal, maxInc, maxVal) ]; } case 'score': return [ ...Fn.map(set.entries(min as number, max as number), entry => entry[1]) ]; default: { const convert = (value: number) => { if (value === Infinity || value === -Infinity) { throw new Error(`Invalid range value: ${value}`); } else if (value < 0) { return set.size + value; } else { return value; } }; return set.values().slice(convert(min as number), convert(max as number) + 1); } } }(); if (options?.limit) { return allMatching.slice(options.limit[0], options.limit[0] + options.limit[1]); } else { return allMatching; } } else { return []; } } zrangeStore(into: string, from: string, min: number | string, max: number | string, options?: P.ZRange) { const set: SortedSet | undefined = this.data.get(from); if (set) { const range: string[] = this.zrange(from, min, max, options); const out = new SortedSet; out.insert(Fn.map(range, member => [ set.score(member)!, member ])); if (out.size === 0) { this.data.delete(into); } else { this.data.set(into, out); } return out.size; } else { return 0; } } zrangeWithScores(key: string, min: number, max: number, options?: P.ZRange) { const set: SortedSet | undefined = this.data.get(key); if (set) { switch (options?.by) { case 'lex': throw new Error('Invalid request'); case 'score': return [ ...set.entries(min, max) ]; default: return [ ...Fn.map(set.values(), (value): [ number, string ] => [ set.score(value)!, value ]) ]; } } else { return []; } } zrem(key: string, members: string[]) { const set: SortedSet | undefined = this.data.get(key); if (set) { const result = Fn.accumulate(members, member => set.delete(member)); if (set.size === 0) { this.data.delete(key); } return result; } else { return 0; } } zremRange(key: string, min: number, max: number) { const set: SortedSet | undefined = this.data.get(key); if (set) { const result = Fn.accumulate( // Results are materialized into array upfront because `delete` invalidates `entries` [ ...Fn.map(set.entries(min, max), entry => entry[1]) ], member => set.delete(member)); if (set.size === 0) { this.data.delete(key); } return result; } else { return 0; } } zscore(key: string, member: string) { const set: SortedSet | undefined = this.data.get(key); if (set) { return set.score(member) ?? null; } else { return null; } } zunionStore(key: string, keys: string[], options?: P.ZAggregate) { const out = new SortedSet; if (options?.weights) { // With WEIGHTS each set needs to be applied one at a time const maybeSets = Fn.map(keys.entries(), ([ index, key ]): [number, SortedSet] => [ options.weights![index] ?? 1, this.data.get(key) ]); const sets = Fn.filter(maybeSets, entry => entry[1]); for (const [ weight, set ] of sets) { out.insert(set.entries(), (left, right) => left + right * weight); } } else { // Without WEIGHTS insert can happen at once const sets = [ ...Fn.filter(Fn.map(keys, (key): SortedSet => this.data.get(key))) ]; out.insert(Fn.concat(Fn.map(sets, set => set.entries()))); } if (out.size === 0) { this.data.delete(key); } else { this.data.set(key, out); } return out.size; } eval(script: KeyvalScript, keys: string[], argv: P.Value[]) { return this.evaluateInline(script.local, keys, argv); } load() {} async evaluateInline(script: string, keys: string[], argv: P.Value[]) { const fn = getOrSet(this.scripts, script, () => { // eslint-disable-next-line @typescript-eslint/no-implied-eval const impl = new Function(`return ${script}`)(); return (instance, keys: string[], argv: P.Value[]) => impl(instance, keys, argv); }); return fn(this, keys, argv); } async flushdb() { await this.blob.flushdb(); this.data.clear(); } async save() { if (this.url) { const payload = JSON.stringify(this.data, (key, value) => { if (value === this.data) { return { '#': 'map', $: Object.fromEntries(Fn.reject(this.data.entries(), entry => this.expires.has(entry[0]))), }; } else if (value instanceof Map) { return { '#': 'map', $: Object.fromEntries(value.entries()) }; } else if (value instanceof Set) { return { '#': 'set', $: [ ...value ] }; } else if (value instanceof SortedSet) { return { '#': 'zset', $: [ ...value.entries() ] }; } else if (ArrayBuffer.isView(value)) { return { '#': 'uint8', $: typedArrayToString(value as Uint8Array) }; } else { return value; } }); const original = new URL(this.url); const tmp = new URL(`./.${original.pathname.substr(original.pathname.lastIndexOf('/') + 1)}.swp`, original); await Promise.all([ this.blob.save(), async function() { await fs.writeFile(tmp, payload, 'utf8'); await fs.rename(tmp, original); }(), ]); } } private remove(key: string) { this.data.delete(key); this.expires.delete(key); } } class LocalKeyValClient extends makeClient(LocalKeyValResponder) { declare get: (...args: any[]) => any; declare req: (...args: any[]) => any; // https://github.com/microsoft/TypeScript/issues/27689 // @ts-expect-error eval(script: KeyvalScript, keys: string[], argv: P.Value[]) { return this.evaluateInline(script.local, keys, argv); } } class LocalKeyValHost extends makeHost(LocalKeyValResponder) { declare get: (...args: any[]) => any; declare req: (...args: any[]) => any; }
the_stack
import {OpenYoloCredential, OpenYoloCredentialHintOptions, OpenYoloCredentialRequestOptions, OpenYoloProxyLoginResponse, RequestContext} from '../protocol/data'; import {OpenYoloInternalError} from '../protocol/errors'; import {SecureChannel} from '../protocol/secure_channel'; import {PromiseResolver, TimeoutRacer} from '../protocol/utils'; import {FakeOpenYoloApi, InitializeOnDemandApi, isCompatibleBrowser, OnDemandOpenYoloApi, openyolo, OpenYoloApi, OpenYoloApiImpl, OpenYoloWithTimeoutApi} from './api'; import {RelayRequest} from './base_request'; import {CancelLastOperationRequest} from './cancel_last_operation_request'; import {CredentialRequest} from './credential_request'; import {CredentialSave} from './credential_save'; import {DisableAutoSignIn} from './disable_auto_sign_in'; import {HintAvailableRequest} from './hint_available_request'; import {HintRequest} from './hint_request'; import {ProviderFrameElement} from './provider_frame_elem'; import {ProxyLogin} from './proxy_login'; type OpenYoloWithTimeoutApiMethods = keyof OpenYoloWithTimeoutApi; describe('OpenYolo API', () => { const credential: OpenYoloCredential = {id: 'test', authMethod: 'test'}; const expectedError = new Error('ERROR!'); const secureChannelSpy = jasmine.createSpyObj('SecureChannel', ['send', 'listen', 'dispose']); describe('setTimeouts', () => { it('raises an error if given a negative number', () => { expect(() => { openyolo.setTimeouts(-1); }).toThrowError(); }); it('resets if changes to disable', () => { spyOn(openyolo, 'reset'); openyolo.setTimeouts(0); expect(openyolo.reset).toHaveBeenCalled(); // Do no call reset a second time. openyolo.setTimeouts(0); expect(openyolo.reset).toHaveBeenCalledTimes(1); }); it('does not reset if changes to positive value', () => { spyOn(openyolo, 'reset'); openyolo.setTimeouts(1); expect(openyolo.reset).not.toHaveBeenCalled(); }); }); describe('initialization', () => { let openYoloApiImplSpy: {[key in OpenYoloWithTimeoutApiMethods]: jasmine.Spy}; beforeEach(() => { openyolo.setTimeouts(null); openYoloApiImplSpy = jasmine.createSpyObj('OpenYoloApiImpl', [ 'hintsAvailable', 'hint', 'retrieve', 'save', 'proxyLogin', 'disableAutoSignIn', 'cancelLastOperation', 'dispose' ]); }); it('allows to initialize again if failed first time', (done) => { spyOn(InitializeOnDemandApi, 'createOpenYoloApi') .and.returnValue(Promise.reject(expectedError)); // The operation does not matter here. openyolo.cancelLastOperation() .then( () => { done.fail('Should not resolve!'); }, (error) => { expect(error).toBe(expectedError); // Successful operation. (InitializeOnDemandApi.createOpenYoloApi as jasmine.Spy) .and.returnValue(Promise.resolve(openYoloApiImplSpy)); // Successful operation. openYoloApiImplSpy.disableAutoSignIn.and.returnValue( Promise.resolve()); return openyolo.cancelLastOperation(); }) .then(done); }); it('secure channel connection fails', (done) => { spyOn(SecureChannel, 'clientConnect') .and.returnValue(Promise.reject(expectedError)); spyOn(ProviderFrameElement.prototype, 'dispose'); // The operation does not matter here. openyolo.cancelLastOperation().then( () => { done.fail('Should not resolve!'); }, (error) => { expect(error).toBe(expectedError); expect(ProviderFrameElement.prototype.dispose).toHaveBeenCalled(); openyolo.reset(); done(); }); }); describe('timeouts', () => { beforeEach(() => { jasmine.clock().install(); }); afterEach(() => { jasmine.clock().uninstall(); }); it('timeouts disabled', (done) => { const promiseResolver = new PromiseResolver<void>(); spyOn(SecureChannel, 'clientConnect') .and.returnValue(promiseResolver.promise); // Avoid using DisableAutoSignIn here as it uses navigator.credentials. spyOn(CancelLastOperationRequest.prototype, 'dispatch') .and.returnValue(Promise.resolve()); openyolo.setTimeouts(0); // The operation does not matter here. openyolo.cancelLastOperation().then( () => { openyolo.reset(); done(); }, (error) => { console.log(error); done.fail('Should not reject!'); }); jasmine.clock().tick(Infinity); promiseResolver.resolve(secureChannelSpy); }); it('custom timeouts set', (done) => { const promiseResolver = new PromiseResolver<void>(); spyOn(SecureChannel, 'clientConnect') .and.returnValue(promiseResolver.promise); let timeoutExpired = false; openyolo.setTimeouts(100); // The operation does not matter here. openyolo.cancelLastOperation().then( () => { done.fail('Should not resolve!'); }, (error) => { expect(timeoutExpired).toBe(true); openyolo.reset(); done(); }); jasmine.clock().tick(99); timeoutExpired = true; jasmine.clock().tick(1); // Does not matter, too late. promiseResolver.resolve(secureChannelSpy); }); }); describe('successful initialization', () => { beforeEach(() => { spyOn(InitializeOnDemandApi, 'createOpenYoloApi') .and.returnValue(Promise.resolve(openYoloApiImplSpy)); }); it('disableAutoSignIn', (done) => { openYoloApiImplSpy.disableAutoSignIn.and.returnValue(Promise.resolve()); openyolo.disableAutoSignIn().then(() => { expect(openYoloApiImplSpy.disableAutoSignIn) .toHaveBeenCalledWith(jasmine.any(Object)); done(); }); }); it('hintsAvailable', (done) => { const options: OpenYoloCredentialHintOptions = {supportedAuthMethods: []}; openYoloApiImplSpy.hintsAvailable.and.returnValue( Promise.resolve(true)); openyolo.hintsAvailable(options).then((result) => { expect(result).toBe(true); expect(openYoloApiImplSpy.hintsAvailable) .toHaveBeenCalledWith(options, jasmine.any(Object)); done(); }); }); it('hint', (done) => { const options: OpenYoloCredentialHintOptions = { supportedAuthMethods: [], context: RequestContext.signIn }; openYoloApiImplSpy.hint.and.returnValue(Promise.resolve(credential)); openyolo.hint(options).then((cred) => { expect(cred).toBe(credential); expect(openYoloApiImplSpy.hint) .toHaveBeenCalledWith(options, jasmine.any(Object)); done(); }); }); it('retrieve', (done) => { const options: OpenYoloCredentialRequestOptions = {supportedAuthMethods: []}; openYoloApiImplSpy.retrieve.and.returnValue( Promise.resolve(credential)); openyolo.retrieve(options).then((cred) => { expect(cred).toBe(credential); expect(openYoloApiImplSpy.retrieve) .toHaveBeenCalledWith(options, jasmine.any(Object)); done(); }); }); it('proxyLogin', (done) => { const expectedResponse: OpenYoloProxyLoginResponse = { statusCode: 200, responseText: 'test' }; openYoloApiImplSpy.proxyLogin.and.returnValue( Promise.resolve(expectedResponse)); openyolo.proxyLogin(credential).then((response) => { expect(response).toBe(expectedResponse); expect(openYoloApiImplSpy.proxyLogin) .toHaveBeenCalledWith(credential, jasmine.any(Object)); done(); }); }); it('save', (done) => { openYoloApiImplSpy.save.and.returnValue(Promise.resolve()); openyolo.save(credential).then(() => { expect(openYoloApiImplSpy.save) .toHaveBeenCalledWith(credential, jasmine.any(Object)); done(); }); }); it('cancelLastOperation', (done) => { openYoloApiImplSpy.cancelLastOperation.and.returnValue( Promise.resolve()); openyolo.cancelLastOperation().then(() => { expect(openYoloApiImplSpy.cancelLastOperation) .toHaveBeenCalledWith(jasmine.any(Object)); done(); }); }); }); }); describe('OpenYoloApiImpl', () => { const wrapBrowserError = OpenYoloInternalError.browserWrappingRequired().toExposedError(); const otherError = OpenYoloInternalError.noCredentialsAvailable().toExposedError(); let openYoloApiImpl: OpenYoloApiImpl; let timeoutRacerSpy: jasmine.SpyObj<TimeoutRacer>; let navCredentialsSpy: jasmine.SpyObj<OpenYoloApi>; beforeEach(() => { navCredentialsSpy = jasmine.createSpyObj('NavigatorCredentials', [ 'hintsAvailable', 'hint', 'retrieve', 'save', 'proxyLogin', 'disableAutoSignIn', 'cancelLastOperation' ]); const frameManager = jasmine.createSpyObj('ProviderFrameElement', ['display']); openYoloApiImpl = new OpenYoloApiImpl( frameManager, secureChannelSpy, navCredentialsSpy); timeoutRacerSpy = jasmine.createSpyObj('TimeoutRacer', ['race', 'hasTimedOut']); }); type methodSignatures = {[key in keyof OpenYoloApi]: typeof OpenYoloApiImpl.prototype[key]}; /** * Tests the behavior of operations implementations. * @param methodName The method of OpenYoloApi being tested. * @param operationRequest The request class's prototype being mocked. * @param options The request's options. * @param expectedResult The expected result when successful. */ function testOperationImpl<M extends keyof methodSignatures, Opt, Res>( methodName: M, operationRequest: RelayRequest<Res, Opt>, options: Opt, expectedResult: Res) { let dispatchSpy: jasmine.Spy; beforeEach(() => { dispatchSpy = spyOn(operationRequest, 'dispatch'); }); it('dispatches the request', (done) => { dispatchSpy.and.returnValue(Promise.resolve(expectedResult)); (openYoloApiImpl[methodName] as methodSignatures[M])( options, timeoutRacerSpy) .then((result: Res) => { expect(result).toBe(expectedResult); expect(dispatchSpy) .toHaveBeenCalledWith(options, timeoutRacerSpy); done(); }); }); it('propagates error', (done) => { timeoutRacerSpy.hasTimedOut.and.returnValue(false); dispatchSpy.and.returnValue(Promise.reject(otherError)); (openYoloApiImpl[methodName] as methodSignatures[M])( options, timeoutRacerSpy) .then( () => { done.fail('Should not resolve!'); }, (error: Error) => { expect(error).toBe(otherError); done(); }); }); it('captures timeout and cancel operation', (done) => { // Simulate timeout error. timeoutRacerSpy.hasTimedOut.and.returnValue(true); dispatchSpy.and.returnValue(Promise.reject(otherError)); spyOn(CancelLastOperationRequest.prototype, 'dispatch'); (openYoloApiImpl[methodName] as methodSignatures[M])( options, timeoutRacerSpy) .then( () => { done.fail('Should not resolve!'); }, (error: Error) => { expect(error).toBe(otherError); expect(CancelLastOperationRequest.prototype.dispatch) .toHaveBeenCalledWith(undefined, undefined); done(); }); }); it('delegates to credential', (done) => { timeoutRacerSpy.hasTimedOut.and.returnValue(false); dispatchSpy.and.returnValue(Promise.reject(wrapBrowserError)); navCredentialsSpy[methodName].and.returnValue( Promise.resolve(expectedResult)); (openYoloApiImpl[methodName] as methodSignatures[M])( options, timeoutRacerSpy) .then((result: Res) => { expect(result).toBe(expectedResult); expect(navCredentialsSpy[methodName]) .toHaveBeenCalledWith(options); done(); }); }); } describe('hintsAvailable', () => { const options: OpenYoloCredentialHintOptions = { supportedAuthMethods: ['https://accounts.google.com'] }; testOperationImpl( 'hintsAvailable', HintAvailableRequest.prototype, options, true); }); describe('hint', () => { const options: OpenYoloCredentialHintOptions = { supportedAuthMethods: ['https://accounts.google.com'] }; testOperationImpl('hint', HintRequest.prototype, options, credential); }); describe('retrieve', () => { const options: OpenYoloCredentialRequestOptions = { supportedAuthMethods: ['https://accounts.google.com'] }; testOperationImpl( 'retrieve', CredentialRequest.prototype, options, credential); }); describe('save', () => { testOperationImpl( 'save', CredentialSave.prototype, credential, undefined); }); describe('proxyLogin', () => { testOperationImpl( 'proxyLogin', ProxyLogin.prototype, credential, undefined); }); describe('cancelLastOperation', () => { let dispatchSpy: jasmine.Spy; beforeEach(() => { dispatchSpy = spyOn(CancelLastOperationRequest.prototype, 'dispatch'); }); it('dispatches the request', (done) => { dispatchSpy.and.returnValue(Promise.resolve()); openYoloApiImpl.cancelLastOperation(timeoutRacerSpy).then(() => { expect(dispatchSpy).toHaveBeenCalledWith(undefined, timeoutRacerSpy); done(); }); }); it('propagates the error', (done) => { dispatchSpy.and.returnValue(Promise.reject(otherError)); openYoloApiImpl.cancelLastOperation(timeoutRacerSpy) .then( () => { done.fail('Should not resolve!'); }, (error) => { expect(error).toBe(otherError); done(); }); }); it('delegates to credential', (done) => { dispatchSpy.and.returnValue(Promise.reject(wrapBrowserError)); navCredentialsSpy.cancelLastOperation.and.returnValue( Promise.resolve()); openYoloApiImpl.cancelLastOperation(timeoutRacerSpy).then(() => { expect(navCredentialsSpy.cancelLastOperation).toHaveBeenCalled(); done(); }); }); }); describe('disableAutoSignIn', () => { it('dispatches the request and calls navigator.credentials', (done) => { spyOn(DisableAutoSignIn.prototype, 'dispatch') .and.returnValue(Promise.resolve()); navCredentialsSpy.disableAutoSignIn.and.returnValue(Promise.resolve()); openYoloApiImpl.disableAutoSignIn(timeoutRacerSpy).then(() => { expect(DisableAutoSignIn.prototype.dispatch) .toHaveBeenCalledWith(undefined, timeoutRacerSpy); expect(navCredentialsSpy.disableAutoSignIn).toHaveBeenCalled(); done(); }); }); it('captures timeout and cancel operation', (done) => { // Simulate timeout error. timeoutRacerSpy.hasTimedOut.and.returnValue(true); spyOn(DisableAutoSignIn.prototype, 'dispatch') .and.returnValue(Promise.reject(otherError)); spyOn(CancelLastOperationRequest.prototype, 'dispatch'); openYoloApiImpl.disableAutoSignIn(timeoutRacerSpy) .then( () => { done.fail('Should not resolve!'); }, (error: Error) => { expect(error).toBe(otherError); expect(CancelLastOperationRequest.prototype.dispatch) .toHaveBeenCalledWith(undefined, undefined); done(); }); }); }); }); describe('FakeOpenYoloApi', () => { const expectedError = OpenYoloInternalError.unsupportedBrowser().toExposedError(); let openYoloApiImpl: OnDemandOpenYoloApi; beforeEach(() => { openYoloApiImpl = new FakeOpenYoloApi(); }); it('rejects hintsAvailable', (done) => { openYoloApiImpl.hintsAvailable({supportedAuthMethods: []}) .then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects hint', (done) => { openYoloApiImpl.hint({supportedAuthMethods: []}) .then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects retrieve', (done) => { openYoloApiImpl.retrieve({supportedAuthMethods: []}) .then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects save', (done) => { openYoloApiImpl.save(credential) .then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects disableAutoSignIn', (done) => { openYoloApiImpl.disableAutoSignIn().then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects cancelLastOperation', (done) => { openYoloApiImpl.cancelLastOperation().then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); it('rejects proxyLogin', (done) => { openYoloApiImpl.proxyLogin(credential) .then( () => { done.fail(); }, (error) => { expect(error).toEqual(expectedError); done(); }); }); }); describe('isCompatibleBrowser', () => { it('crypto available', () => { const windowWithCrypto = { crypto: {getRandomValues: () => {}, subtle: {}} }; expect(isCompatibleBrowser(windowWithCrypto as any)).toBe(true); }); it('getRandomValues not available', () => { const windowWithCrypto = {crypto: {subtle: {}}}; expect(isCompatibleBrowser(windowWithCrypto as any)).toBe(false); }); it('subtle not available', () => { const windowWithCrypto = {crypto: {getRandomValues: () => {}}}; expect(isCompatibleBrowser(windowWithCrypto as any)).toBe(false); }); it('subtle not available, webkitSubtle available', () => { const windowWithCrypto = { crypto: {getRandomValues: () => {}, webkitSubtle: {}} }; expect(isCompatibleBrowser(windowWithCrypto as any)).toBe(true); }); }); });
the_stack
import * as TH from './type-helpers'; import { AsyncActionCreatorBuilder } from './type-helpers'; import { createAsyncAction } from './create-async-action'; type User = { firstName: string; lastName: string }; // @dts-jest:group async action without cancel { const fetchUsersAsync = createAsyncAction( 'FETCH_USERS_REQUEST', 'FETCH_USERS_SUCCESS', 'FETCH_USERS_FAILURE' )<undefined, User[], Error>(); // @dts-jest:pass:snap -> TH.EmptyAction<"FETCH_USERS_REQUEST"> fetchUsersAsync.request(); /* => { type: 'FETCH_USERS_REQUEST' } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_SUCCESS", User[]> fetchUsersAsync.success([ { firstName: 'Piotr', lastName: 'Witek' }, ]); /* => { type: 'FETCH_USERS_SUCCESS', payload: [{ firstName: 'Piotr', lastName: 'Witek' }] } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_FAILURE", Error> fetchUsersAsync.failure( Error('reason') ); /* => { type: 'FETCH_USERS_FAILURE', payload: Error('reason') } */ // @dts-jest:fail:snap -> Property 'cancel' does not exist on type '{ request: EmptyActionCreator<"FETCH_USERS_REQUEST">; success: PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: PayloadActionCreator<...>; }'. fetchUsersAsync.cancel; const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USERS_REQUEST', undefined], ['FETCH_USERS_SUCCESS', User[]], ['FETCH_USERS_FAILURE', Error] > ) => { a.request; a.success; a.failure; // @ts-ignore a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.EmptyActionCreator<"FETCH_USERS_REQUEST">; success: TH.PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: TH.PayloadActionCreator<"FETCH_USERS_FAILURE", Error>; } fn(fetchUsersAsync); } // @dts-jest:group async action with any type { const fetchUsersAsync = createAsyncAction( 'FETCH_USERS_REQUEST', 'FETCH_USERS_SUCCESS', 'FETCH_USERS_FAILURE' )<any, any[], any>(); // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_REQUEST", any> fetchUsersAsync.request( 1 ); /* => { type: 'FETCH_USERS_REQUEST', payload: 1, } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_SUCCESS", any[]> fetchUsersAsync.success([ 1, ]); /* => { type: 'FETCH_USERS_SUCCESS', payload: [1], } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_FAILURE", any> fetchUsersAsync.failure( 1 ); /* => { type: 'FETCH_USERS_FAILURE', payload: 1, } */ // @dts-jest:fail:snap -> Property 'cancel' does not exist on type '{ request: PayloadActionCreator<"FETCH_USERS_REQUEST", any>; success: PayloadActionCreator<"FETCH_USERS_SUCCESS", any[]>; failure: PayloadActionCreator<...>; }'. fetchUsersAsync.cancel; const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USERS_REQUEST', any], ['FETCH_USERS_SUCCESS', any[]], ['FETCH_USERS_FAILURE', any] > ) => { a.request; a.success; a.failure; // @ts-ignore a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.PayloadActionCreator<"FETCH_USERS_REQUEST", any>; success: TH.PayloadActionCreator<"FETCH_USERS_SUCCESS", any[]>; failure: TH.PayloadActionCreator<"FETCH_USERS_FAILURE", any>; } fn(fetchUsersAsync); } // @dts-jest:group async action with cancel { const fetchUsersAsync = createAsyncAction( 'FETCH_USERS_REQUEST', 'FETCH_USERS_SUCCESS', 'FETCH_USERS_FAILURE', 'FETCH_USERS_CANCEL' )<undefined, User[], Error, string>(); // @dts-jest:pass:snap -> TH.EmptyAction<"FETCH_USERS_REQUEST"> fetchUsersAsync.request(); /* => { type: 'FETCH_USERS_REQUEST' } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_SUCCESS", User[]> fetchUsersAsync.success([ { firstName: 'Piotr', lastName: 'Witek' }, ]); /* => { type: 'FETCH_USERS_SUCCESS', payload: [{ firstName: 'Piotr', lastName: 'Witek' }] } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_FAILURE", Error> fetchUsersAsync.failure( Error('reason') ); /* => { type: 'FETCH_USERS_FAILURE', payload: Error('reason') } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_CANCEL", string> fetchUsersAsync.cancel( 'reason' ); /* => { type: 'FETCH_USERS_CANCEL', payload: 'reason' } */ const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USERS_REQUEST', undefined], ['FETCH_USERS_SUCCESS', User[]], ['FETCH_USERS_FAILURE', Error], ['FETCH_USERS_CANCEL', string] > ) => { { a.request; a.success; a.failure; a.cancel; return a; } }; // @dts-jest:pass:snap -> { request: TH.EmptyActionCreator<"FETCH_USERS_REQUEST">; success: TH.PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: TH.PayloadActionCreator<"FETCH_USERS_FAILURE", Error>; cancel: TH.PayloadActionCreator<"FETCH_USERS_CANCEL", string>; } fn(fetchUsersAsync); } // @dts-jest:group async action with meta { const fetchUsersAsync = createAsyncAction( 'FETCH_USERS_REQUEST', 'FETCH_USERS_SUCCESS', 'FETCH_USERS_FAILURE' )<[undefined, number], User[], [Error, number]>(); // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USERS_REQUEST", undefined, number> fetchUsersAsync.request( undefined, 111 ); /* => { type: 'FETCH_USERS_REQUEST', meta: 111 } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_SUCCESS", User[]> fetchUsersAsync.success([ { firstName: 'Piotr', lastName: 'Witek' }, ]); /* => { type: 'FETCH_USERS_SUCCESS', payload: [{ firstName: 'Piotr', lastName: 'Witek' }] } */ // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USERS_FAILURE", Error, number> fetchUsersAsync.failure( Error('reason'), 111 ); /* => { type: 'FETCH_USERS_FAILURE', payload: Error('reason'), meta: 111 } */ // @dts-jest:fail:snap -> Property 'cancel' does not exist on type '{ request: PayloadMetaActionCreator<"FETCH_USERS_REQUEST", undefined, number>; success: PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: PayloadMetaActionCreator<...>; }'. fetchUsersAsync.cancel; const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USERS_REQUEST', [undefined, number]], ['FETCH_USERS_SUCCESS', User[]], ['FETCH_USERS_FAILURE', [Error, number]] > ) => { a.request; a.success; a.failure; // @ts-ignore a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.PayloadMetaActionCreator<"FETCH_USERS_REQUEST", undefined, number>; success: TH.PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: TH.PayloadMetaActionCreator<"FETCH_USERS_FAILURE", Error, number>; } fn(fetchUsersAsync); } // @dts-jest:group async action with meta with cancel { const fetchUsersAsync = createAsyncAction( 'FETCH_USERS_REQUEST', 'FETCH_USERS_SUCCESS', 'FETCH_USERS_FAILURE', 'FETCH_USERS_CANCEL' )<[undefined, number], User[], [Error, number], string>(); // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USERS_REQUEST", undefined, number> fetchUsersAsync.request( undefined, 111 ); /* => { type: 'FETCH_USERS_REQUEST', meta: 111 } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_SUCCESS", User[]> fetchUsersAsync.success([ { firstName: 'Piotr', lastName: 'Witek' }, ]); /* => { type: 'FETCH_USERS_SUCCESS', payload: [{ firstName: 'Piotr', lastName: 'Witek' }] } */ // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USERS_FAILURE", Error, number> fetchUsersAsync.failure( Error('reason'), 111 ); /* => { type: 'FETCH_USERS_FAILURE', payload: Error('reason'), meta: 111 } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USERS_CANCEL", string> fetchUsersAsync.cancel( 'reason' ); /* => { type: 'FETCH_USERS_CANCEL', payload: 'reason' } */ const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USERS_REQUEST', [undefined, number]], ['FETCH_USERS_SUCCESS', User[]], ['FETCH_USERS_FAILURE', [Error, number]], ['FETCH_USERS_CANCEL', string] > ) => { a.request; a.success; a.failure; a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.PayloadMetaActionCreator<"FETCH_USERS_REQUEST", undefined, number>; success: TH.PayloadActionCreator<"FETCH_USERS_SUCCESS", User[]>; failure: TH.PayloadMetaActionCreator<"FETCH_USERS_FAILURE", Error, number>; cancel: TH.PayloadActionCreator<"FETCH_USERS_CANCEL", string>; } fn(fetchUsersAsync); } // @dts-jest:group async action with mappers { const fetchUserMappers = createAsyncAction( 'FETCH_USER_REQUEST', [ 'FETCH_USER_SUCCESS', ({ firstName, lastName }: User) => `${firstName} ${lastName}`, ], [ 'FETCH_USER_FAILURE', (error: Error, meta: number) => error, (error: Error, meta: number) => meta, ] )(); // @dts-jest:pass:snap -> TH.EmptyAction<"FETCH_USER_REQUEST"> fetchUserMappers.request(); /* => { type: 'FETCH_USER_REQUEST' } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USER_SUCCESS", string> fetchUserMappers.success({ firstName: 'Piotr', lastName: 'Witek', }); /* => { type: 'FETCH_USER_SUCCESS', payload: 'Piotr Witek', } */ // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USER_FAILURE", Error, number> fetchUserMappers.failure( Error('reason'), 111 ); /* => { type: 'FETCH_USER_FAILURE', payload: Error('reason'), meta: 111 } */ // @dts-jest:fail:snap -> Property 'cancel' does not exist on type '{ request: EmptyActionCreator<"FETCH_USER_REQUEST">; success: (__0: User) => PayloadAction<"FETCH_USER_SUCCESS", string>; failure: (error: Error, meta: number) => PayloadMetaAction<...>; }'. fetchUserMappers.cancel; const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USER_REQUEST', undefined], ['FETCH_USER_SUCCESS', [User], string], ['FETCH_USER_FAILURE', [Error, number], [Error, number]] > ) => { a.request; a.success; a.failure; // @ts-ignore a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.EmptyActionCreator<"FETCH_USER_REQUEST">; success: (args_0: User) => TH.PayloadAction<"FETCH_USER_SUCCESS", string>; failure: (args_0: Error, args_1: number) => TH.PayloadMetaAction<"FETCH_USER_FAILURE", Error, number>; } fn(fetchUserMappers); } // @dts-jest:group async action with mappers with cancel { const fetchUserMappers = createAsyncAction( 'FETCH_USER_REQUEST', [ 'FETCH_USER_SUCCESS', ({ firstName, lastName }: User) => `${firstName} ${lastName}`, ], [ 'FETCH_USER_FAILURE', (error: Error, meta: number) => error, (error: Error, meta: number) => meta, ], ['FETCH_USER_CANCEL', undefined, (meta: number) => meta] )(); // @dts-jest:pass:snap -> TH.EmptyAction<"FETCH_USER_REQUEST"> fetchUserMappers.request(); /* => { type: 'FETCH_USER_REQUEST' } */ // @dts-jest:pass:snap -> TH.PayloadAction<"FETCH_USER_SUCCESS", string> fetchUserMappers.success({ firstName: 'Piotr', lastName: 'Witek', }); /* => { type: 'FETCH_USER_SUCCESS', payload: 'Piotr Witek', } */ // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USER_FAILURE", Error, number> fetchUserMappers.failure( Error('reason'), 111 ); /* => { type: 'FETCH_USER_FAILURE', payload: Error('reason'), meta: 111 } */ // @dts-jest:pass:snap -> TH.PayloadMetaAction<"FETCH_USER_CANCEL", undefined, number> fetchUserMappers.cancel( 111 ); /* => { type: 'FETCH_USER_CANCEL', meta: 111 } */ const fn = ( a: AsyncActionCreatorBuilder< ['FETCH_USER_REQUEST', undefined], ['FETCH_USER_SUCCESS', [User], string], ['FETCH_USER_FAILURE', [Error, number], [Error, number]], ['FETCH_USER_CANCEL', [number], [undefined, number]] > ) => { a.request; a.success; a.failure; a.cancel; return a; }; // @dts-jest:pass:snap -> { request: TH.EmptyActionCreator<"FETCH_USER_REQUEST">; success: (args_0: User) => TH.PayloadAction<"FETCH_USER_SUCCESS", string>; failure: (args_0: Error, args_1: number) => TH.PayloadMetaAction<"FETCH_USER_FAILURE", Error, number>; cancel: (args_0: number) => TH.PayloadMetaAction<"FETCH_USER_CANCEL", undefined, number>; } fn(fetchUserMappers); }
the_stack
import { AggregatedError } from "./aggregatederror"; import { TokenSource } from "./tokensource"; import { DurableError } from "./durableerror"; import { EntityId, ITaskMethods, RetryOptions, Task, TimerTask, CallActivityAction, CallActivityWithRetryAction, CallEntityAction, CallHttpAction, CallSubOrchestratorAction, CallSubOrchestratorWithRetryAction, ContinueAsNewAction, CreateTimerAction, DurableHttpRequest, EventRaisedEvent, EventSentEvent, ExternalEventType, GuidManager, HistoryEvent, HistoryEventType, RequestMessage, ResponseMessage, SubOrchestrationInstanceCompletedEvent, SubOrchestrationInstanceCreatedEvent, SubOrchestrationInstanceFailedEvent, TaskCompletedEvent, TaskFactory, TaskFailedEvent, TaskFilter, TaskScheduledEvent, TimerCreatedEvent, TimerFiredEvent, WaitForExternalEventAction, } from "./classes"; import { CompletedTask, TaskBase } from "./tasks/taskinterfaces"; /** * Parameter data for orchestration bindings that can be used to schedule * function-based activities. */ export class DurableOrchestrationContext { constructor( state: HistoryEvent[], instanceId: string, currentUtcDateTime: Date, isReplaying: boolean, parentInstanceId: string | undefined, input: unknown ) { this.state = state; this.instanceId = instanceId; this.isReplaying = isReplaying; this.currentUtcDateTime = currentUtcDateTime; this.parentInstanceId = parentInstanceId; this.input = input; this.newGuidCounter = 0; this.subOrchestratorCounter = 0; } private input: unknown; private readonly state: HistoryEvent[]; private newGuidCounter: number; private subOrchestratorCounter: number; public customStatus: unknown; /** * The ID of the current orchestration instance. * * The instance ID is generated and fixed when the orchestrator function is * scheduled. It can be either auto-generated, in which case it is * formatted as a GUID, or it can be user-specified with any format. */ public readonly instanceId: string; /** * The ID of the parent orchestration of the current sub-orchestration * instance. The value will be available only in sub-orchestrations. * * The parent instance ID is generated and fixed when the parent * orchestrator function is scheduled. It can be either auto-generated, in * which case it is formatted as a GUID, or it can be user-specified with * any format. */ public readonly parentInstanceId: string | undefined; /** * Gets a value indicating whether the orchestrator function is currently * replaying itself. * * This property is useful when there is logic that needs to run only when * the orchestrator function is _not_ replaying. For example, certain types * of application logging may become too noisy when duplicated as part of * orchestrator function replay. The orchestrator code could check to see * whether the function is being replayed and then issue the log statements * when this value is `false`. */ public isReplaying: boolean; /** * Gets the current date/time in a way that is safe for use by orchestrator * functions. * * This date/time value is derived from the orchestration history. It * always returns the same value at specific points in the orchestrator * function code, making it deterministic and safe for replay. */ public currentUtcDateTime: Date; /** * Just an entry point to reference the methods in [[ITaskMethods]]. * Methods to handle collections of pending actions represented by [[Task]] * instances. For use in parallelization operations. */ public Task: ITaskMethods = { all: (tasks: TaskBase[]) => { let maxCompletionIndex: number | undefined; const errors: Error[] = []; const results: Array<unknown> = []; for (const task of tasks) { if (!TaskFilter.isCompletedTask(task)) { return TaskFactory.UncompletedTaskSet(tasks); } if (!maxCompletionIndex) { maxCompletionIndex = task.completionIndex; } else if (maxCompletionIndex < task.completionIndex) { maxCompletionIndex = task.completionIndex; } if (TaskFilter.isFailedTask(task)) { errors.push(task.exception); } else { results.push(task.result); } } // We are guaranteed that maxCompletionIndex is not undefined, or // we would have alreayd returned an uncompleted task set. const completionIndex = maxCompletionIndex as number; if (errors.length > 0) { return TaskFactory.FailedTaskSet( tasks, completionIndex, new AggregatedError(errors) ); } else { return TaskFactory.SuccessfulTaskSet(tasks, completionIndex, results); } }, any: (tasks: Task[]) => { if (!tasks || tasks.length === 0) { throw new Error("At least one yieldable task must be provided to wait for."); } let firstCompleted: CompletedTask | undefined; for (const task of tasks) { if (TaskFilter.isCompletedTask(task)) { if (!firstCompleted) { firstCompleted = task; } else if (task.completionIndex < firstCompleted.completionIndex) { firstCompleted = task; } } } if (firstCompleted) { return TaskFactory.SuccessfulTaskSet( tasks, firstCompleted.completionIndex, firstCompleted ); } else { return TaskFactory.UncompletedTaskSet(tasks); } }, }; /** * Schedules an activity function named `name` for execution. * * @param name The name of the activity function to call. * @param input The JSON-serializable input to pass to the activity * function. * @returns A Durable Task that completes when the called activity * function completes or fails. */ public callActivity(name: string, input?: unknown): Task { const newAction = new CallActivityAction(name, input); const taskScheduled = this.findTaskScheduled(this.state, name); const taskCompleted = this.findTaskCompleted(this.state, taskScheduled); const taskFailed = this.findTaskFailed(this.state, taskScheduled); this.setProcessed([taskScheduled, taskCompleted, taskFailed]); if (taskCompleted) { const result = this.parseHistoryEvent(taskCompleted); return TaskFactory.SuccessfulTask( newAction, result, taskCompleted.Timestamp, taskCompleted.TaskScheduledId, this.state.indexOf(taskCompleted) ); } else if (taskFailed) { return TaskFactory.FailedTask( newAction, taskFailed.Reason, taskFailed.Timestamp, taskFailed.TaskScheduledId, this.state.indexOf(taskFailed), new DurableError(taskFailed.Reason) ); } else { return TaskFactory.UncompletedTask(newAction); } } /** * Schedules an activity function named `name` for execution with * retry options. * * @param name The name of the activity function to call. * @param retryOptions The retry options for the activity function. * @param input The JSON-serializable input to pass to the activity * function. */ public callActivityWithRetry(name: string, retryOptions: RetryOptions, input?: unknown): Task { const newAction = new CallActivityWithRetryAction(name, retryOptions, input); let attempt = 1; let taskScheduled: TaskScheduledEvent | undefined; let taskFailed: TaskFailedEvent | undefined; let taskRetryTimer: TimerCreatedEvent | undefined; for (let i = 0; i < this.state.length; i++) { const historyEvent = this.state[i]; if (historyEvent.IsProcessed) { continue; } if (!taskScheduled) { if (historyEvent.EventType === HistoryEventType.TaskScheduled) { if ((historyEvent as TaskScheduledEvent).Name === name) { taskScheduled = historyEvent as TaskScheduledEvent; } } continue; } if (historyEvent.EventType === HistoryEventType.TaskCompleted) { if ( (historyEvent as TaskCompletedEvent).TaskScheduledId === taskScheduled.EventId ) { const taskCompleted = historyEvent as TaskCompletedEvent; this.setProcessed([taskScheduled, taskCompleted]); const result = this.parseHistoryEvent(taskCompleted); return TaskFactory.SuccessfulTask( newAction, result, taskCompleted.Timestamp, taskCompleted.TaskScheduledId, i ); } else { continue; } } if (!taskFailed) { if (historyEvent.EventType === HistoryEventType.TaskFailed) { if ( (historyEvent as TaskFailedEvent).TaskScheduledId === taskScheduled.EventId ) { taskFailed = historyEvent as TaskFailedEvent; } } continue; } if (!taskRetryTimer) { if (historyEvent.EventType === HistoryEventType.TimerCreated) { taskRetryTimer = historyEvent as TimerCreatedEvent; } else { continue; } } if (historyEvent.EventType === HistoryEventType.TimerFired) { if ((historyEvent as TimerFiredEvent).TimerId === taskRetryTimer.EventId) { const taskRetryTimerFired = historyEvent as TimerFiredEvent; this.setProcessed([ taskScheduled, taskFailed, taskRetryTimer, taskRetryTimerFired, ]); if (attempt >= retryOptions.maxNumberOfAttempts) { return TaskFactory.FailedTask( newAction, taskFailed.Reason, taskFailed.Timestamp, taskFailed.TaskScheduledId, i, new DurableError(taskFailed.Reason) ); } else { attempt++; taskScheduled = undefined; taskFailed = undefined; taskRetryTimer = undefined; } } else { continue; } } } return TaskFactory.UncompletedTask(newAction); } /** * Calls an operation on an entity, passing an argument, and waits for it * to complete. * * @param entityId The target entity. * @param operationName The name of the operation. * @param operationInput The input for the operation. */ public callEntity(entityId: EntityId, operationName: string, operationInput?: unknown): Task { const newAction = new CallEntityAction(entityId, operationName, operationInput); const schedulerId = EntityId.getSchedulerIdFromEntityId(entityId); const eventSent = this.findEventSent(this.state, schedulerId, "op"); let eventRaised; if (eventSent) { const eventSentInput = eventSent && eventSent.Input ? (JSON.parse(eventSent.Input) as RequestMessage) : undefined; eventRaised = eventSentInput ? this.findEventRaised(this.state, eventSentInput.id) : undefined; } this.setProcessed([eventSent, eventRaised]); if (eventRaised) { const parsedResult = this.parseHistoryEvent(eventRaised) as ResponseMessage; return TaskFactory.SuccessfulTask( newAction, JSON.parse(parsedResult.result), eventRaised.Timestamp, eventSent.EventId, this.state.indexOf(eventRaised) ); } // TODO: error handling return TaskFactory.UncompletedTask(newAction); } /** * Schedules an orchestration function named `name` for execution. * * @param name The name of the orchestrator function to call. * @param input The JSON-serializable input to pass to the orchestrator * function. * @param instanceId A unique ID to use for the sub-orchestration instance. * If `instanceId` is not specified, the extension will generate an id in * the format `<calling orchestrator instance ID>:<#>` */ public callSubOrchestrator(name: string, input?: unknown, instanceId?: string): Task { if (!name) { throw new Error( "A sub-orchestration function name must be provided when attempting to create a suborchestration" ); } const newAction = new CallSubOrchestratorAction(name, instanceId, input); const subOrchestratorCreated = this.findSubOrchestrationInstanceCreated( this.state, name, instanceId ); const subOrchestratorCompleted = this.findSubOrchestrationInstanceCompleted( this.state, subOrchestratorCreated ); const subOrchestratorFailed = this.findSubOrchestrationInstanceFailed( this.state, subOrchestratorCreated ); this.setProcessed([ subOrchestratorCreated, subOrchestratorCompleted, subOrchestratorFailed, ]); if (subOrchestratorCompleted) { const result = this.parseHistoryEvent(subOrchestratorCompleted); return TaskFactory.SuccessfulTask( newAction, result, subOrchestratorCompleted.Timestamp, subOrchestratorCompleted.TaskScheduledId, this.state.indexOf(subOrchestratorCompleted) ); } else if (subOrchestratorFailed) { return TaskFactory.FailedTask( newAction, subOrchestratorFailed.Reason, subOrchestratorFailed.Timestamp, subOrchestratorFailed.TaskScheduledId, this.state.indexOf(subOrchestratorFailed), new DurableError(subOrchestratorFailed.Reason) ); } else { return TaskFactory.UncompletedTask(newAction); } } /** * Schedules an orchestrator function named `name` for execution with retry * options. * * @param name The name of the orchestrator function to call. * @param retryOptions The retry options for the orchestrator function. * @param input The JSON-serializable input to pass to the orchestrator * function. * @param instanceId A unique ID to use for the sub-orchestration instance. */ public callSubOrchestratorWithRetry( name: string, retryOptions: RetryOptions, input?: unknown, instanceId?: string ): Task { if (!name) { throw new Error( "A sub-orchestration function name must be provided when attempting to create a suborchestration" ); } const newAction = new CallSubOrchestratorWithRetryAction( name, retryOptions, input, instanceId ); let attempt = 1; let subOrchestratorCreated: SubOrchestrationInstanceCreatedEvent | undefined; let subOrchestratorFailed: SubOrchestrationInstanceFailedEvent | undefined; let taskRetryTimer: TimerCreatedEvent | undefined; for (let i = 0; i < this.state.length; i++) { const historyEvent = this.state[i]; if (historyEvent.IsProcessed) { continue; } if (!subOrchestratorCreated) { if (historyEvent.EventType === HistoryEventType.SubOrchestrationInstanceCreated) { const subOrchEvent = historyEvent as SubOrchestrationInstanceCreatedEvent; if ( subOrchEvent.Name === name && (!instanceId || instanceId === subOrchEvent.InstanceId) ) { subOrchestratorCreated = subOrchEvent; } } continue; } if (historyEvent.EventType === HistoryEventType.SubOrchestrationInstanceCompleted) { if ( (historyEvent as SubOrchestrationInstanceCompletedEvent).TaskScheduledId === subOrchestratorCreated.EventId ) { const subOrchCompleted = historyEvent as SubOrchestrationInstanceCompletedEvent; this.setProcessed([subOrchestratorCreated, subOrchCompleted]); const result = this.parseHistoryEvent(subOrchCompleted); return TaskFactory.SuccessfulTask( newAction, result, subOrchCompleted.Timestamp, subOrchCompleted.TaskScheduledId, i ); } else { continue; } } if (!subOrchestratorFailed) { if (historyEvent.EventType === HistoryEventType.SubOrchestrationInstanceFailed) { if ( (historyEvent as SubOrchestrationInstanceFailedEvent).TaskScheduledId === subOrchestratorCreated.EventId ) { subOrchestratorFailed = historyEvent as SubOrchestrationInstanceFailedEvent; } } continue; } if (!taskRetryTimer) { if (historyEvent.EventType === HistoryEventType.TimerCreated) { taskRetryTimer = historyEvent as TimerCreatedEvent; } continue; } if (historyEvent.EventType === HistoryEventType.TimerFired) { if ((historyEvent as TimerFiredEvent).TimerId === taskRetryTimer.EventId) { const taskRetryTimerFired = historyEvent as TimerFiredEvent; this.setProcessed([ subOrchestratorCreated, subOrchestratorFailed, taskRetryTimer, taskRetryTimerFired, ]); if (attempt >= retryOptions.maxNumberOfAttempts) { return TaskFactory.FailedTask( newAction, subOrchestratorFailed.Reason, subOrchestratorFailed.Timestamp, subOrchestratorFailed.TaskScheduledId, i, new DurableError(subOrchestratorFailed.Reason) ); } else { attempt += 1; subOrchestratorCreated = undefined; subOrchestratorFailed = undefined; taskRetryTimer = undefined; } } else { continue; } } } return TaskFactory.UncompletedTask(newAction); } /** * Schedules a durable HTTP call to the specified endpoint. * * @param req The durable HTTP request to schedule. */ public callHttp( method: string, uri: string, content?: string | object, headers?: { [key: string]: string }, tokenSource?: TokenSource ): Task { if (content && typeof content !== "string") { content = JSON.stringify(content); } const req = new DurableHttpRequest(method, uri, content as string, headers, tokenSource); const newAction = new CallHttpAction(req); // callHttp is internally implemented as a well-known activity function const httpScheduled = this.findTaskScheduled(this.state, "BuiltIn::HttpActivity"); const httpCompleted = this.findTaskCompleted(this.state, httpScheduled); const httpFailed = this.findTaskFailed(this.state, httpScheduled); this.setProcessed([httpScheduled, httpCompleted, httpFailed]); if (httpCompleted) { const result = this.parseHistoryEvent(httpCompleted); return TaskFactory.SuccessfulTask( newAction, result, httpCompleted.Timestamp, httpCompleted.TaskScheduledId, this.state.indexOf(httpCompleted) ); } else if (httpFailed) { return TaskFactory.FailedTask( newAction, httpFailed.Reason, httpFailed.Timestamp, httpFailed.TaskScheduledId, this.state.indexOf(httpFailed), new DurableError(httpFailed.Reason) ); } else { return TaskFactory.UncompletedTask(newAction); } } /** * Restarts the orchestration by clearing its history. * * @param The JSON-serializable data to re-initialize the instance with. */ public continueAsNew(input: unknown): Task { const newAction = new ContinueAsNewAction(input); return TaskFactory.UncompletedTask(newAction); } /** * Creates a durable timer that expires at a specified time. * * All durable timers created using this method must either expire or be * cancelled using [[TimerTask]].[[cancel]] before the orchestrator * function completes. Otherwise, the underlying framework will keep the * instance alive until the timer expires. * * Timers currently cannot be scheduled further than 7 days into the * future. * * @param fireAt The time at which the timer should expire. * @returns A TimerTask that completes when the durable timer expires. */ public createTimer(fireAt: Date): TimerTask { const newAction = new CreateTimerAction(fireAt); const timerCreated = this.findTimerCreated(this.state, fireAt); const timerFired = this.findTimerFired(this.state, timerCreated); this.setProcessed([timerCreated, timerFired]); if (timerFired) { return TaskFactory.CompletedTimerTask( newAction, timerFired.Timestamp, timerFired.TimerId, this.state.indexOf(timerFired) ); } else { return TaskFactory.UncompletedTimerTask(newAction); } } /** * Gets the input of the current orchestrator function as a deserialized * value. */ public getInput<T>(): T { return this.input as T; } /** * Creates a new GUID that is safe for replay within an orchestration or * operation. * * The default implementation of this method creates a name-based UUID * using the algorithm from RFC 4122 §4.3. The name input used to generate * this value is a combination of the orchestration instance ID and an * internally managed sequence number. */ public newGuid(instanceId: string): string { const guidNameValue = `${instanceId}_${this.currentUtcDateTime.valueOf()}_${ this.newGuidCounter }`; this.newGuidCounter++; return GuidManager.createDeterministicGuid(GuidManager.UrlNamespaceValue, guidNameValue); } /** * Sets the JSON-serializable status of the current orchestrator function. * * The `customStatusObject` value is serialized to JSON and will be made * available to the orchestration status query APIs. The serialized JSON * value must not exceed 16 KB of UTF-16 encoded text. * * The serialized `customStatusObject` value will be made available to the * aforementioned APIs after the next `yield` or `return` statement. * * @param customStatusObject The JSON-serializable value to use as the * orchestrator function's custom status. */ public setCustomStatus(customStatusObject: unknown): void { this.customStatus = customStatusObject; } /** * Waits asynchronously for an event to be raised with the name `name` and * returns the event data. * * External clients can raise events to a waiting orchestration instance * using [[raiseEvent]]. */ public waitForExternalEvent(name: string): Task { const newAction = new WaitForExternalEventAction(name, ExternalEventType.ExternalEvent); const eventRaised = this.findEventRaised(this.state, name); this.setProcessed([eventRaised]); if (eventRaised) { const result = this.parseHistoryEvent(eventRaised); return TaskFactory.SuccessfulTask( newAction, result, eventRaised.Timestamp, eventRaised.EventId, this.state.indexOf(eventRaised) ); } else { return TaskFactory.UncompletedTask(newAction); } } // =============== /* Returns undefined if not found. */ private findEventRaised(state: HistoryEvent[], eventName: string): EventRaisedEvent { const returnValue = eventName ? state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.EventRaised && (val as EventRaisedEvent).Name === eventName && !val.IsProcessed ); })[0] : undefined; return returnValue as EventRaisedEvent; } /* Returns undefined if not found. */ private findEventSent( state: HistoryEvent[], instanceId: string, eventName: string ): EventSentEvent { const returnValue = eventName ? state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.EventSent && (val as EventSentEvent).InstanceId === instanceId && (val as EventSentEvent).Name === eventName && !val.IsProcessed ); })[0] : undefined; return returnValue as EventSentEvent; } /* Returns undefined if not found. */ private findSubOrchestrationInstanceCreated( state: HistoryEvent[], name: string, instanceId: string | undefined ): SubOrchestrationInstanceCreatedEvent | undefined { const matches = state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.SubOrchestrationInstanceCreated && !val.IsProcessed ); }); if (matches.length === 0) { return undefined; } this.subOrchestratorCounter++; // Grab the first unprocessed sub orchestration creation event and verify that // it matches the same function name and instance id if provided. If not, we know that // we have nondeterministic behavior, because the callSubOrchestrator*() methods were not // called in the same order this replay that they were scheduled in. const returnValue = matches[0] as SubOrchestrationInstanceCreatedEvent; if (returnValue.Name !== name) { throw new Error( `The sub-orchestration call (n = ${this.subOrchestratorCounter}) should be executed with a function name of ${returnValue.Name} instead of the provided function name of ${name}. Check your code for non-deterministic behavior.` ); } if (instanceId && returnValue.InstanceId !== instanceId) { throw new Error( `The sub-orchestration call (n = ${this.subOrchestratorCounter}) should be executed with an instance id of ${returnValue.InstanceId} instead of the provided instance id of ${instanceId}. Check your code for non-deterministic behavior.` ); } return returnValue; } /* Returns undefined if not found. */ private findSubOrchestrationInstanceCompleted( state: HistoryEvent[], createdSubOrch: SubOrchestrationInstanceCreatedEvent | undefined ): SubOrchestrationInstanceCompletedEvent | undefined { if (createdSubOrch === undefined) { return undefined; } const matches = state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.SubOrchestrationInstanceCompleted && (val as SubOrchestrationInstanceCompletedEvent).TaskScheduledId === createdSubOrch.EventId && !val.IsProcessed ); }); return matches.length > 0 ? (matches[0] as SubOrchestrationInstanceCompletedEvent) : undefined; } /* Returns undefined if not found. */ private findSubOrchestrationInstanceFailed( state: HistoryEvent[], createdSubOrchInstance: SubOrchestrationInstanceCreatedEvent | undefined ): SubOrchestrationInstanceFailedEvent | undefined { if (createdSubOrchInstance === undefined) { return undefined; } const matches = state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.SubOrchestrationInstanceFailed && (val as SubOrchestrationInstanceFailedEvent).TaskScheduledId === createdSubOrchInstance.EventId && !val.IsProcessed ); }); return matches.length > 0 ? (matches[0] as SubOrchestrationInstanceFailedEvent) : undefined; } /* Returns undefined if not found. */ private findTaskScheduled(state: HistoryEvent[], name: string): TaskScheduledEvent | undefined { const returnValue = name ? (state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.TaskScheduled && (val as TaskScheduledEvent).Name === name && !val.IsProcessed ); })[0] as TaskScheduledEvent) : undefined; return returnValue; } /* Returns undefined if not found. */ private findTaskCompleted( state: HistoryEvent[], scheduledTask: TaskScheduledEvent | undefined ): TaskCompletedEvent | undefined { if (scheduledTask === undefined) { return undefined; } const returnValue = scheduledTask ? (state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.TaskCompleted && (val as TaskCompletedEvent).TaskScheduledId === scheduledTask.EventId ); })[0] as TaskCompletedEvent) : undefined; return returnValue; } /* Returns undefined if not found. */ private findTaskFailed( state: HistoryEvent[], scheduledTask: TaskScheduledEvent | undefined ): TaskFailedEvent | undefined { if (scheduledTask === undefined) { return undefined; } const returnValue = scheduledTask ? (state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.TaskFailed && (val as TaskFailedEvent).TaskScheduledId === scheduledTask.EventId ); })[0] as TaskFailedEvent) : undefined; return returnValue; } /* Returns undefined if not found. */ private findTimerCreated(state: HistoryEvent[], fireAt: Date): TimerCreatedEvent { const returnValue = fireAt ? state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.TimerCreated && new Date((val as TimerCreatedEvent).FireAt).getTime() === fireAt.getTime() ); })[0] : undefined; return returnValue as TimerCreatedEvent; } /* Returns undefined if not found. */ private findTimerFired( state: HistoryEvent[], createdTimer: TimerCreatedEvent | undefined ): TimerFiredEvent | undefined { const returnValue = createdTimer ? (state.filter((val: HistoryEvent) => { return ( val.EventType === HistoryEventType.TimerFired && (val as TimerFiredEvent).TimerId === createdTimer.EventId ); })[0] as TimerFiredEvent) : undefined; return returnValue; } private setProcessed(events: Array<HistoryEvent | undefined>): void { events.map((val: HistoryEvent | undefined) => { if (val) { val.IsProcessed = true; } }); } private parseHistoryEvent(directiveResult: HistoryEvent): unknown { let parsedDirectiveResult: unknown; switch (directiveResult.EventType) { case HistoryEventType.EventRaised: const eventRaised = directiveResult as EventRaisedEvent; parsedDirectiveResult = eventRaised && eventRaised.Input ? JSON.parse(eventRaised.Input) : undefined; break; case HistoryEventType.SubOrchestrationInstanceCompleted: parsedDirectiveResult = JSON.parse( (directiveResult as SubOrchestrationInstanceCompletedEvent).Result ); break; case HistoryEventType.TaskCompleted: parsedDirectiveResult = JSON.parse((directiveResult as TaskCompletedEvent).Result); break; default: break; } return parsedDirectiveResult; } }
the_stack
import { Client } from '@src/core' import { Endpoints } from '@src/constants' import { MessageCreateData } from '@src/api/entities/message/interfaces/MessageCreateData' import { GatewayOpCodes, RestFinishedResponse } from '@discordoo/providers' import { RawMessageData } from '@src/api/entities/message/interfaces/RawMessageData' import { RawEmojiEditData } from '@src/api/entities/emoji/interfaces/RawEmojiEditData' import { RawGuildEmojiData } from '@src/api/entities/emoji/interfaces/RawGuildEmojiData' import { RawStickerData } from '@src/api/entities/sticker/interfaces/RawStickerData' import { RawUserData } from '@src/api/entities/user/interfaces/RawUserData' import { RawStickerEditData } from '@src/api/entities/sticker/interfaces/RawStickerEditData' import { RawStickerCreateData } from '@src/api/entities/sticker/interfaces/RawStickerCreateData' import { RawStickerPackData } from '@src/api/entities/sticker' import { RawGuildMemberEditData } from '@src/api/entities/member/interfaces/RawGuildMemberEditData' import { GuildMember, RawGuildMemberData } from '@src/api' import { RawRoleEditData } from '@src/api/entities/role/interfaces/RawRoleEditData' import { RawRoleData } from '@src/api/entities/role/interfaces/RawRoleData' import { RawRoleCreateData } from '@src/api/entities/role/interfaces/RawRoleCreateData' import { FetchReactionUsersOptions } from '@src/api/managers/reactions/FetchReactionUsersOptions' import { RawGuildChannelEditData } from '@src/api/entities/channel/interfaces/RawGuildChannelEditData' import { RawAbstractGuildChannelData } from '@src/api/entities/channel/interfaces/RawAbstractGuildChannelData' import { RawThreadChannelEditData } from '@src/api/entities/channel/interfaces/RawThreadChannelEditData' import { RawPermissionOverwriteData } from '@src/api/entities/overwrites/interfaces/RawPermissionOverwriteData' import { RawGuildChannelCreateData } from '@src/api/entities/channel/interfaces/RawGuildChannelCreateData' import { RawThreadChannelWithMessageCreateData } from '@src/api/entities/channel/interfaces/RawThreadChannelWithMessageCreateData' import { RawThreadChannelCreateData } from '@src/api/entities/channel/interfaces/RawThreadChannelCreateData' import { FetchManyMessagesQuery } from '@src/api/managers/messages/FetchManyMessagesQuery' import { RawGuildMembersFetchOptions } from '@src/api/managers/members/RawGuildMembersFetchOptions' import { GuildMembersChunkEventContext } from '@src/events' import { DiscordooError, DiscordSnowflake, ValidationError } from '@src/utils' import { GuildMembersChunkHandlerContext } from '@src/events/interfaces/GuildMembersChunkHandlerContext' import { is } from 'typescript-is' import { RawGuildMemberAddData } from '@src/api/managers/members/RawGuildMemberAddData' export class ClientActions { public client: Client constructor(client: Client) { this.client = client } addGuildDiscoverySubcategory(guildId: string, categoryId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_DISCOVERY_CATEGORY(guildId, categoryId)) .post({ reason }) } // returns guild member data or empty string addGuildMember(guildId: string, memberId: string, data: RawGuildMemberAddData) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER(guildId, memberId)) .body(data) .put<RawGuildMemberData | string>() } addGuildMemberRole(guildId: string, memberId: string, roleId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER_ROLE(guildId, memberId, roleId)) .put({ reason }) } addReaction(channelId: string, messageId: string, emojiId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelId, messageId, emojiId, '@me')) .put() } addThreadMember(channelId: string, memberId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_THREAD_MEMBER(channelId, memberId)) .put() } addFollower(senderId: string, followerId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_FOLLOW(senderId)) .body({ webhook_channel_id: followerId }) .post({ reason }) } removeThreadMember(channelId: string, memberId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_THREAD_MEMBER(channelId, memberId)) .delete() } banGuildMember(guildId: string, userId: string, deleteMessagesDays = 0, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_BAN(guildId, userId)) .body({ delete_message_days: deleteMessagesDays }) .post({ reason }) } createGuild(name: string, data: any /* TODO: GuildCreateData */) { return this.client.internals.rest.api() .url(Endpoints.GUILDS()) .body({ name, region: data.region, icon: data.icon, verification_level: data.verificationLevel, default_message_notifications: data.defaultNotifications, explicit_content_filter: data.explicitContentFilter, system_channel_id: data.systemChannelId, afk_channel_id: data.afkChannelId, afk_timeout: data.afkTimeout, roles: data.roles, channels: data.channels, }) .post() } createGuildChannel(guildId: string, data: RawGuildChannelCreateData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_CHANNELS(guildId)) .body(data) .post({ reason }) } createGuildEmoji(guildId: string, data: any /* TODO: GuildEmojiData */, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_EMOJIS(guildId)) .body(data) .post({ reason }) } createGuildRole(guildId: string, data: RawRoleCreateData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_ROLES(guildId)) .body(data) .post<RawRoleData>({ reason }) } createGuildFromTemplate(code: string, name: string, icon?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATE(code)) .body({ name, icon }) .post() } createGuildTemplate(guildId: string, name: string, description?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATES(guildId)) .body({ name, description }) .post() } createThreadWithMessage(channelId: string, data: RawThreadChannelWithMessageCreateData, reason?: string) { const request = this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_THREADS(channelId, data.message_id)) delete (data as any).message_id request.body(data) return request.post({ reason }) } createThread(channelId: string, data: RawThreadChannelCreateData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_THREADS(channelId)) .body(data) .post({ reason }) } createMessage(channelId: string, data: MessageCreateData): RestFinishedResponse<RawMessageData> { const request = this.client.internals.rest.api().url(Endpoints.CHANNEL_MESSAGES(channelId)) if (data.files.length) { request.attach(...data.files) } request.body({ content: data.content, tts: data.tts, embeds: data.embeds?.length ? data.embeds : undefined, allowed_mentions: data.allowed_mentions, message_reference: data.message_reference, sticker_ids: data.stickers, components: data.components }) return request.post() } createGuildSticker(guildId: string, data: RawStickerCreateData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_STICKERS(guildId)) .body({ name: data.name, description: data.description, tags: data.tags }) .attach(data.file) .post<RawStickerData>({ reason }) } deleteChannel(channelId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL(channelId)) .delete({ reason }) } deleteChannelPermissions(channelId: string, overwriteId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_PERMISSION(channelId, overwriteId)) .delete({ reason }) } deleteGuild(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD(guildId)) .delete() } deleteMessage(channelId: string, messageId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE(channelId, messageId)) .delete({ reason }) } deleteMessagesBulk(channelId: string, messages: string[], reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_BULK_DELETE(channelId)) .body({ messages }) .post({ reason }) } deleteGuildEmoji(guildId: string, emojiId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_EMOJI(guildId, emojiId)) .delete({ reason }) } deleteGuildRole(guildId: string, roleId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_ROLE(guildId, roleId)) .delete({ reason }) } deleteGuildIntegration(guildId: string, integrationId: string) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_INTEGRATION(guildId, integrationId)) .delete() } deleteGuildTemplate(guildId: string, code: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATE_GUILD(guildId, code)) .delete() } deleteGuildSticker(guildId: string, stickerId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_STICKER(guildId, stickerId)) .delete({ reason }) } editGuild(guildId: string, data: any /* TODO: GuildData */, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD(guildId)) .body({ name: data.name, region: data.region, icon: data.icon, verification_level: data.verificationLevel, default_message_notifications: data.defaultNotifications, explicit_content_filter: data.explicitContentFilter, system_channel_id: data.systemChannelId, system_channel_flags: data.systemChannelFlags, rules_channel_id: data.rulesChannelId, public_updates_channel_id: data.publicUpdatesChannelId, preferred_locale: data.preferredLocale, afk_channel_id: data.afkChannelId, afk_timeout: data.afkTimeout, owner_id: data.ownerId, splash: data.splash, banner: data.banner, description: data.description, discovery_splash: data.discoverySplash, features: data.features, }) .patch({ reason }) } editGuildChannel(channelId: string, data: RawGuildChannelEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL(channelId)) .body(data) .patch<RawAbstractGuildChannelData>({ reason }) } editGuildChannelPermissions(channelId: string, data: RawPermissionOverwriteData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_PERMISSION(channelId, data.id)) .body({ allow: data.allow, deny: data.deny, type: data.type, }) .put({ reason }) } editThreadChannel(channelId: string, data: RawThreadChannelEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL(channelId)) .body(data) .patch({ reason }) } editGuildDiscovery(guildId: string, data: any /* TODO: GuildDiscoveryData */, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_DISCOVERY(guildId)) .body({ primary_category_id: data.primaryCategoryId, keywords: data.keywords, emoji_discoverability_enabled: data.emojiDiscoverabilityEnabled, }) .patch({ reason }) } editGuildEmoji(guildId: string, emojiId: string, data: RawEmojiEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_EMOJI(guildId, emojiId)) .body(data) .patch<RawGuildEmojiData>({ reason }) } // TODO: Check if reason available editGuildIntegration(guildId: string, integrationId: string, data: any /* TODO: GuildIntegrationData */) { return this.client.internals.rest.api() .url(Endpoints.GUILD_INTEGRATION(guildId, integrationId)) .body({ expire_behavior: data.expireBehavior, expire_grace_period: data.expireGracePeriod, enable_emoticons: data.enableEmoticons, }) .patch() } editGuildMember(guildId: string, userId: string, data: RawGuildMemberEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER(guildId, userId)) .body(data) .patch<RawGuildMemberData>({ reason }) } editGuildRole(guildId: string, roleId: string, data: RawRoleEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_ROLE(guildId, roleId)) .body(data) .patch<RawRoleData>({ reason }) } editGuildTemplate(guildId: string, code: string, data: any /* TODO: GuildTemplateData */) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATE_GUILD(guildId, code)) .body(data) .patch() } editGuildVanity(guildId: string, code: string) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_VANITY_URL(guildId)) .body({ code }) .patch() } editGuildVoiceState(guildId: string, data: any /* TODO: GuildVoiceStateData */, user = '@me') { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_VOICE_STATE(guildId, user)) .body({ channel_id: data.channelId, request_to_speak_timestamp: data.requestToSpeakTimestamp, suppress: data.suppress, }) .patch() } editGuildWelcomeScreen(guildId: string, data: any /* TODO: GuildWelcomeScreenData */) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_WELCOME_SCREEN(guildId)) .body({ description: data.description, enabled: data.enabled, welcome_screens: data.welcomeScreens.map((c) => ({ channel_id: c.channelId, description: c.description, emoji_id: c.emojiId, emoji_name: c.emojiName, })), }) .patch() } editGuildWidget(guildId: string, data: any /* TODO: GuildWidgetData */, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_WIDGET(guildId)) .body(data) .patch({ reason }) } editGuildSticker(guildId: string, stickerId: string, data: RawStickerEditData, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_STICKER(guildId, stickerId)) .body(data) .patch<RawStickerData>({ reason }) } getReactionUsers( channelId: string, messageId: string, emojiId: string, options?: FetchReactionUsersOptions ): RestFinishedResponse<RawUserData[]> { const request = this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, emojiId)) if (typeof options?.limit === 'number') { request.query({ limit: options.limit }) } if (typeof options?.after === 'string') { request.query({ after: options.after }) } return request.get<RawUserData[]>() } getPinnedMessages(channelId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_PINS(channelId)) .get<RawMessageData[]>() } getMessage(channelId: string, messageId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE(channelId, messageId)) .get<RawMessageData>() } getMessages(channelId: string, query: FetchManyMessagesQuery) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGES(channelId)) .query(query) .get<RawMessageData[]>() } getGuildAuditLog(guildId: string, data: any /* TODO: GetGuildAuditLogData */) { return this.client.internals.rest.api() .url(Endpoints.GUILD_AUDIT_LOGS(guildId)) .query({ user_id: data.userId, action_type: data.actionType, before: data.before, limit: data.limit, }) .get() } getChannel(channelId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL(channelId)) .get() } getGuildBan(guildId: string, memberId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_BAN(guildId, memberId)) .get() } getGuildBans(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_BANS(guildId)) .get() } getGuildDiscovery(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_DISCOVERY(guildId)) .get() } getGuildRoles(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_ROLES(guildId)) .get<RawRoleData[]>() } getGuildIntegrations(guildId: string, data: any /* TODO: GetGuildIntegrationsData */ = {}) { return this.client.internals.rest.api() .url(Endpoints.GUILD_INTEGRATIONS(guildId)) .query({ include_applications: data.includeApplications ?? false, }) .get() } getGuildInvites(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_INVITES(guildId)) .get() } getGuildMember(guildId: string, memberId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER(guildId, memberId)) .get<RawGuildMemberData>() } fetchWsGuildMembers(shardId: number, options: RawGuildMembersFetchOptions): Promise<GuildMember[]> { if (!is<RawGuildMembersFetchOptions>(options)) { throw new ValidationError(undefined, 'Invalid members fetch options')._setInvalidOptions(options) } if (isNaN(shardId)) { throw new ValidationError(undefined, 'Invalid shardId for fetching members:', shardId) } const nonce = options.nonce ?? DiscordSnowflake.generate() let context: any return new Promise((resolve, reject) => { const handler = (eventContext: GuildMembersChunkEventContext, executionContext: GuildMembersChunkHandlerContext) => { if (eventContext.nonce === executionContext.nonce) { executionContext.fetched.push(eventContext.members) executionContext.timeout.refresh() } if (eventContext.last) { clearTimeout(executionContext.timeout) executionContext.resolve(executionContext.fetched.flat()) return true } return executionContext } const timeout = setTimeout(() => { if (this.client.internals.queues.members.has(nonce)) { this.client.internals.queues.members.delete(nonce) const err = new DiscordooError(undefined, 'Guild members fetching stopped due to timeout.') reject(err) } }, 120_000) context = { handler, timeout, resolve, reject, nonce, fetched: [] } this.client.internals.queues.members.set(nonce, context) this.client.internals.gateway.send({ op: GatewayOpCodes.REQUEST_GUILD_MEMBERS, d: { ...options, nonce } }, { shards: [ shardId ]}) }) } getGuildPreview(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_PREVIEW(guildId)) .get() } getGuildTemplate(code: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATE(code)) .get() } getGuildVanity(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_VANITY_URL(guildId)) .get() } getGuildWebhooks(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_WEBHOOKS(guildId)) .get() } getGuildWelcomeScreen(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_WELCOME_SCREEN(guildId)) .get() } getGuildWidget(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_WIDGET(guildId)) .get() } getGuildEmoji(guildId: string, emojiId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_EMOJI(guildId, emojiId)) .get<RawGuildEmojiData>() } getGuildSticker(guildId: string, stickerId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_STICKER(guildId, stickerId)) .get<RawStickerData>() } getGuildStickers(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_STICKERS(guildId)) .get<RawStickerData[]>() } getSticker(stickerId: string) { return this.client.internals.rest.api() .url(Endpoints.STICKER(stickerId)) .get<RawStickerData>() } getNitroStickerPacks() { return this.client.internals.rest.api() .url(Endpoints.NITRO_STICKERS()) .get<RawStickerPackData[]>() } getUser(userId: string) { return this.client.internals.rest.api() .url(Endpoints.USER(userId)) .get<RawUserData>() } kickGuildMember(guildId: string, memberId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER(guildId, memberId)) .delete({ reason }) } leaveGuild(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.USER_GUILD('@me', guildId)) .delete() } listGuildMembers(guildId: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBERS(guildId)) .get<RawGuildMemberData[]>() } pruneGuildMembers(guildId: string, data: any /* GuildMembersPruneData */ = {}, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_PRUNE(guildId)) .body({ days: data.days, compute_prune_count: data.computePruneCount, include_roles: data.includeRoles, }) .delete({ reason }) } pinMessage(channelId: string, messageId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_PIN(channelId, messageId)) .put({ reason }) } removeGuildMemberRole(guildId: string, memberId: string, roleId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBER_ROLE(guildId, memberId, roleId)) .delete({ reason }) } removeReactionUsers(channelId: string, messageId: string, emojiId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, emojiId)) .delete() } removeReactionUser(channelId: string, messageId: string, emojiId: string, userId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_REACTION_USER(channelId, messageId, emojiId, userId)) .delete() } removeReactions(channelId: string, messageId: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_MESSAGE_REACTIONS(channelId, messageId)) .delete() } searchGuildMembers(guildId: string, data: any /* TODO: GuildMembersSearchData */) { return this.client.internals.rest.api() .url(Endpoints.GUILD_MEMBERS_SEARCH(guildId)) .query({ query: data.query, limit: data.limit, }) .get() } syncGuildIntegration(guildId: string, integrationId: string) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_INTEGRATION_SYNC(guildId, integrationId)) .post() } syncGuildTemplate(guildId: string, code: string) { // TODO: check if reason available return this.client.internals.rest.api() .url(Endpoints.GUILD_TEMPLATE_GUILD(guildId, code)) .put() } unbanGuildMember(guildId: string, memberId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.GUILD_BAN(guildId, memberId)) .delete({ reason }) } unpinMessage(channelId: string, messageId: string, reason?: string) { return this.client.internals.rest.api() .url(Endpoints.CHANNEL_PIN(channelId, messageId)) .delete({ reason }) } }
the_stack
namespace LiteMol.Bootstrap.Tree { "use strict"; import Node = Tree.Node.Any; export interface Transformer<A extends Node, B extends Node, P> { info: Transformer.Info<A, B, P>; apply(context: Context, a: A, t: Transform<A, B, P>): Task<B> update(context: Context, b: B, t: Transform<A, B, P>): Task<B> create(params: P, props?: Transform.Props): Transform<A, B, P>; } export namespace Transformer { export type Any = Transformer<Node, Node, any> export interface Info<A extends Node, B extends Node, P> { id: string, name: string, description: string, isUpdatable?: boolean, from: Tree.Node.TypeOf<A>[], to: Tree.Node.TypeOf<B>[], validateParams?: (params: P) => string[] | undefined, // return undefined if everything is fine, array of strings with issues otherwise defaultParams: (ctx: Context, e: A) => P | undefined, customController?: (ctx: Context, transformer: Transformer<A, B, P>, entity: Entity.Any) => Components.Transform.Controller<P>, isApplicable?: (e: A) => boolean, isComposed?: boolean } class TransformerImpl<A extends Node, B extends Node, P> implements Transformer<A, B, P> { private getTarget(node: A) { let info = this.info; return (!info.from.length ? node : Node.findClosestNodeOfType(node, info.from)) as A; } private checkTypes(a: A, t: Transform<A, B, P>) { if (t.transformer !== this) { return `The transform is calling an invalid transformer (got ${t.transformer.info.name}, expected ${this.info.name})`; } let info = this.info; if (info.from.length && info.from.indexOf(a.type) < 0) { return `Transform (${info.name}): type error, expected '${info.from.map(t => t.info.name).join('/')}', got '${a.type.info.name}'.`; } return void 0; } private validateParams(t: Transform<A, B, P>) { let info = this.info; if (info.validateParams) { let issues = info.validateParams(t.params); if (issues && issues.length > 0) { return `Invalid params: ${issues.join(', ')}.`; } } return void 0; } private validate(a: A, t: Transform<A, B, P>) { let info = this.info; if (!a) return Task.reject(info.name, 'Normal', 'Could not find a suitable node to apply the transformer to.'); let typeCheck = this.checkTypes(a, t); if (typeCheck) return Task.reject(info.name, 'Normal', typeCheck); let paramValidation = this.validateParams(t); if (paramValidation) return Task.reject(info.name, 'Normal', paramValidation); return void 0; } apply(context: Context, node: A, t: Transform<A, B, P>): Task<B> { if (this.info.isComposed) return this.transform(context, node, t); let a = this.getTarget(node); let validationFailed = this.validate(a, t); if (validationFailed) return validationFailed as Task<B>; Event.Tree.TransformerApply.dispatch(context, { a, t }); return this.transform(context, a, t); } update(context: Context, b: B, t: Transform<A, B, P>): Task<B> { let node = b.parent; if (this.info.isComposed && !this.updater) return this.transform(context, node as A, t); if (this.updater) { let paramValidation = this.validateParams(t); if (paramValidation) return Task.reject(this.info.name, 'Normal', paramValidation); let updated = this.updater(context, b, t); if (updated) return updated; } Event.Tree.TransformerApply.dispatch(context, { a: b.parent, t }); return this.transform(context, node as A, t); } create(params: P, props?: Transform.Props): Transform<A, B, P> { return Transform.create<A, B, P>(params, props ? props : {}, this); } constructor( public info: Transformer.Info<A, B, P>, private transform: (ctx: Context, a: A, t: Transform<A, B, P>) => Task<B>, private updater?: (ctx: Context, b: B, t: Transform<A, B, P>) => Task<B> | undefined) { } } export function create<A extends Node, B extends Node, P>( info: Info<A, B, P>, transform: (ctx: Context, a: A, t: Transform<A, B, P>) => Task<B>, updater?: (ctx: Context, b: B, t: Transform<A, B, P>) => Task<B> | undefined): Transformer<A, B, P> { return new TransformerImpl(info, transform, updater); } export function internal<A extends Node, B extends Node, P>( id: string, from: Tree.Node.TypeOf<A>[], to: Tree.Node.TypeOf<B>[], transform: (ctx: Context, a: A, t: Transform<A, B, P>) => Task<B> ) { return create<Entity.Root, Entity.Root, {}>({ id, name: id, description: '', from, to, validateParams: () => void 0, defaultParams: () => ({ }) }, transform); } export interface ActionWithContext<T> { action: Transform.Source, context: T } function rejectAction<T>( actionContext: T, error: any, context: Context, reject: (e: any) => void, onError?: string | ((ctx: Context, actionCtx: T | undefined, error: any) => void)) { try { reject(error); } finally { if (onError) { if (typeof onError === 'string') { context.logger.error(onError); } else { setTimeout(() => onError.call(null, context, actionContext, error), 0); } } } } async function resolveAction<T>( src: ActionWithContext<T>, context: Context, resolve: (e: Entity.Action) => void, reject: (e: any) => void, onDone?: string | ((ctx: Context, actionCtx: T | undefined) => void), onError?: string | ((ctx: Context, actionCtx: T | undefined, error: any) => void)) { let hadError = false; try { await Tree.Transform.apply(context, src.action).run(); try { resolve(Tree.Node.Null) } finally { if (onDone) { if (typeof onDone === 'string') { if (!hadError) context.logger.message(onDone); } else { setTimeout(() => onDone.call(null, context, src.context), 0); } } } } catch (e) { hadError = true; try { reject(e); } finally { if (onError) { if (typeof onError === 'string') { context.logger.error(onError); } else { setTimeout(() => onError.call(null, context, src.context, e), 0); } } } } } export function action<A extends Node, B extends Node, P>( info: Info<A, B, P>, builder: (ctx: Context, a: A, t: Transform<A, B, P>) => Transform.Source, onDone?: string, onError?: string): Transformer<A, B, P> { return create(info, (context, a, t) => { return Task.create<Entity.Action>(info.name, 'Background', ctx => new Promise((res, rej) => { try { let src = builder(context, a, t); resolveAction<undefined>({ action: src, context: void 0 }, context, res, rej, onDone, onError); } catch (e) { rej(e); } })) as Task<B>; }) } export function actionWithContext<A extends Node, B extends Node, P, T>( info: Info<A, B, P>, builder: (ctx: Context, a: A, t: Transform<A, B, P>) => ActionWithContext<T> | Promise<ActionWithContext<T>>, onDone?: (ctx: Context, actionCtx: T | undefined) => void, onError?: (ctx: Context, actionCtx: T | undefined, error: any) => void): Transformer<A, B, P> { return create(info, (context, a, t) => { return Task.create<Entity.Action>(info.name, 'Background', ctx => new Promise((res, rej) =>{ try { let src = builder(context, a, t); if (Task.isPromise(src)) { src .then(s => resolveAction<T>(s, context, res, rej, onDone, onError)) .catch(e => rejectAction<undefined>(void 0, e, context, rej, onError)); } else { resolveAction<T>(src, context, res, rej, onDone, onError) } } catch (e) { rej(e); } })) as Task<B>; }) } } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type SaleArtworkTileRailCardTestsQueryVariables = {}; export type SaleArtworkTileRailCardTestsQueryResponse = { readonly saleArtwork: { readonly " $fragmentRefs": FragmentRefs<"SaleArtworkTileRailCard_saleArtwork">; } | null; }; export type SaleArtworkTileRailCardTestsQuery = { readonly response: SaleArtworkTileRailCardTestsQueryResponse; readonly variables: SaleArtworkTileRailCardTestsQueryVariables; }; /* query SaleArtworkTileRailCardTestsQuery { saleArtwork(id: "the-sale") { ...SaleArtworkTileRailCard_saleArtwork id } } fragment SaleArtworkTileRailCard_saleArtwork on SaleArtwork { artwork { artistNames date href image { imageURL: url(version: "small") aspectRatio } internalID slug saleMessage title id } counts { bidderPositions } currentBid { display } lotLabel sale { isAuction isClosed displayTimelyAt id } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "the-sale" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v3 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v4 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "SaleArtworkTileRailCardTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "SaleArtworkTileRailCard_saleArtwork" } ], "storageKey": "saleArtwork(id:\"the-sale\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "SaleArtworkTileRailCardTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": "imageURL", "args": [ { "kind": "Literal", "name": "version", "value": "small" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"small\")" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "saleMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "isAuction", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isClosed", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayTimelyAt", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, (v1/*: any*/) ], "storageKey": "saleArtwork(id:\"the-sale\")" } ] }, "params": { "id": "96febd82056beb8a2264e84e64a0312f", "metadata": { "relayTestingSelectionTypeInfo": { "saleArtwork": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtwork" }, "saleArtwork.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "saleArtwork.artwork.artistNames": (v2/*: any*/), "saleArtwork.artwork.date": (v2/*: any*/), "saleArtwork.artwork.href": (v2/*: any*/), "saleArtwork.artwork.id": (v3/*: any*/), "saleArtwork.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "saleArtwork.artwork.image.aspectRatio": { "enumValues": null, "nullable": false, "plural": false, "type": "Float" }, "saleArtwork.artwork.image.imageURL": (v2/*: any*/), "saleArtwork.artwork.internalID": (v3/*: any*/), "saleArtwork.artwork.saleMessage": (v2/*: any*/), "saleArtwork.artwork.slug": (v3/*: any*/), "saleArtwork.artwork.title": (v2/*: any*/), "saleArtwork.counts": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCounts" }, "saleArtwork.counts.bidderPositions": { "enumValues": null, "nullable": true, "plural": false, "type": "FormattedNumber" }, "saleArtwork.currentBid": { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCurrentBid" }, "saleArtwork.currentBid.display": (v2/*: any*/), "saleArtwork.id": (v3/*: any*/), "saleArtwork.lotLabel": (v2/*: any*/), "saleArtwork.sale": { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, "saleArtwork.sale.displayTimelyAt": (v2/*: any*/), "saleArtwork.sale.id": (v3/*: any*/), "saleArtwork.sale.isAuction": (v4/*: any*/), "saleArtwork.sale.isClosed": (v4/*: any*/) } }, "name": "SaleArtworkTileRailCardTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '6984680176745967effebe8d3fdbcccb'; export default node;
the_stack
module TDev.AST { // update library references export class SplitAppIntoAppAndLibrary { constructor() { this.ddManager = new DeclAndDepsManager(); } private ddManager: DeclAndDepsManager = null; private theApp: App = null; private targetLibrary: LibraryRef = null; private declsSelectedToMove: DeclAndDeps[] = []; private otherDeclsToMove: DeclAndDeps[] = []; private remainingDecls: DeclAndDeps[] = null; public appRewritten: string = null public library: string = null; public getAllDeclsToMove(): DeclAndDeps[]{ return this.declsSelectedToMove.concat(this.otherDeclsToMove); } public getRemainingDecls(): DeclAndDeps[] { return this.remainingDecls; } private programChanged(): boolean { var all = this.ddManager.getAll().filter(dd => !(dd.decl instanceof LibraryRef)); if (all.length == this.theApp.things.length) { var ret = true; this.theApp.things.forEach(d => { ret = ret && d.cachedSerialized.idx >= 0; }); this.ddManager.getAll().forEach(dd => { ret = ret && this.theApp.things.indexOf(dd.decl) >= 0; }); return ret; } else { return false; } } public invalidate() { // we should only do this if the program changed (it's an expensive operation) if (this.targetLibrary != null && this.programChanged()) { this.ddManager.invalidate(); // get rid of all derived information this.otherDeclsToMove = []; // "" this.remainingDecls = null; // "" var remove = []; this.ddManager.getAll().forEach(dd => { if (this.theApp.things.indexOf(dd.decl) < 0) { remove.push(dd); } }); remove.forEach(dd => { this.ddManager.remove(dd); var idx = this.declsSelectedToMove.indexOf(dd); if (idx >= 0) this.declsSelectedToMove.splice(idx); }); // add back the require elements this.addToDeclsToMove(this.declsSelectedToMove); } } public getAll(): DeclAndDeps[] { return this.ddManager.getAll(); } public getter(d: Decl): DeclAndDeps { return this.ddManager.getter(d); } public setAppAndLib(a: App, l: LibraryRef): boolean { if (this.targetLibrary == null) { this.theApp = a; this.targetLibrary = l; return true; } else { return false; } } public getApp(): App { return this.theApp; } public getLib(): LibraryRef { return this.targetLibrary; } public addToDeclsToMove(newOnes: DeclAndDeps[]) { // we ensure that declsToMove always is downwards closed, // which means that the split into app/library is well-defined var theRest = this.computeClosure(newOnes); newOnes.forEach(dd => { if (this.declsSelectedToMove.indexOf(dd) < 0) { this.declsSelectedToMove.push(dd) } }); theRest.forEach(dd => { if (this.declsSelectedToMove.indexOf(dd) < 0 && this.otherDeclsToMove.indexOf(dd) < 0) { this.otherDeclsToMove.push(dd) } }); this.computeRemaining(); } public computeClosure(roots: DeclAndDeps[]): DeclAndDeps[] { return this.computeClosureRaw(roots, this.getAllDeclsToMove()); } private computeRemaining() { if (this.remainingDecls == null) { this.remainingDecls = []; this.theApp.things.forEach(t => { if (!(t instanceof Action && (<Action>t).isEvent())) { var dd = this.ddManager.getter(t); if (this.getAllDeclsToMove().indexOf(dd) < 0) { this.remainingDecls.push(dd); } } }); } else { this.remainingDecls = this.remainingDecls.filter((a) => this.getAllDeclsToMove().indexOf(a) < 0); } } private computeClosureRaw(roots: DeclAndDeps[], alreadyIn: DeclAndDeps[]) { var theRest = []; DeclAndDeps.computeClosure(roots, alreadyIn, theRest); return theRest.filter(dd => dd.decl != this.targetLibrary); } public makeSplit() { // sanity checks if (this.targetLibrary == null || this.getAllDeclsToMove() == []) return; // which library actions will be public? var actions = this.getAllDeclsToMove().filter(dd => dd.decl instanceof Action); actions.forEach(dd => (<Action>dd.decl).isPrivate = true); this.remainingDecls.filter(dd => dd.decl instanceof Action).forEach(a => { // check for calls into library from app and make actions public as needed a.getActions().forEach(b => { if (actions.indexOf(b) >= 0) { var act = <Action>b.decl; act.isPrivate = false; // if parameter of b is a callback, make it public // (this is a special case that we might generalize later // if record types and other types can be exported from // library concretely) act.getInParameters().forEach(p => { if (p.local.getKind() instanceof UserActionKind) { (<UserActionKind>p.local.getKind()).userAction.isPrivate = false; } }); } }); }); // keep a copy of originals in case user wants to revert this.getAllDeclsToMove().forEach(dd => { dd.serialized = dd.decl.serialize(); }); // we need to rewrite the decls that depend on target library to remove the library reference var removeTarget = new RemoveLibraryReference(this.targetLibrary); this.getAllDeclsToMove().forEach(dd => removeTarget.dispatch(dd.decl)); // create the accessor functions that will permit application to // access the fields/properties of the hidden data var accessors = new CreateAccessors( this.theApp, this.getAllDeclsToMove().filter(dd => !(dd.decl instanceof Action)).map(dd => dd.decl), this.remainingDecls); // add the accessors to the library accessors.getAccessorActions().forEach(act => this.targetLibrary.resolved.addDecl(act)); // rewrite the application (given the accessor information) var rewriter = new RewriteApp(this.targetLibrary, actions.map(dd => dd.decl), accessors); rewriter.performRewrite(this.theApp); // move everything to library // NOTE: we are assuming that there are no name conflicts with things already in the library var libraryReferences = []; this.getAllDeclsToMove().forEach((dd) => { if (dd.decl != this.targetLibrary && dd.decl.parent == this.theApp) { var decls = AST.Parser.parseDecls(dd.decl.serialize(), this.targetLibrary.resolved); decls.forEach(d => { if (d instanceof LibraryRef) { if (libraryReferences.indexOf(d) < 0) { libraryReferences.push(d); this.targetLibrary.resolved.addDecl(d); } } else { this.targetLibrary.resolved.addDecl(d); } }); } }); // resolve any new library references we've added to the target library this.targetLibrary.initializeResolves(); // delete the decls that have been copied ('cept for LibraryRefs) this.getAllDeclsToMove().forEach(dd => { if (!(dd.decl instanceof LibraryRef)) { this.theApp.deleteDecl(dd.decl); dd.decl = null; } else { // in order to delete a library reference, we need // to show that it's no longer needed in the application } }); // save the app and library InitIdVisitor.ensureOK(this.theApp) InitIdVisitor.ensureOK(this.targetLibrary.resolved) this.appRewritten = this.theApp.serialize(); this.library = this.targetLibrary.resolved.serialize(); // TODO: for testing, we will want to check that the above are syntactically // TODO: and semantically correct. } } class CreateAccessors { constructor( public theApp: App, public declsToLibrary: Decl[], public remaining: DeclAndDeps[]) { // go through the actions that remain in the application to see // what globals/fields/properties they access of decls that are // moving to the library remaining.forEach(dd => { dd.direct.readGlobals.forEach(rg => this.addGlobal(rg, "R")); dd.direct.writtenGlobals.forEach(wg => this.addGlobal(wg, "W")); dd.direct.readFields.forEach(rf => { var stmt = rf.forwardsToStmt(); this.addField(<RecordField>stmt, "R"); }); dd.direct.readProps.forEach((rp, i) => { this.addProperty(rp, dd.direct.readPropsWhat[i]); }); dd.direct.writtenFields.forEach(wp => { var stmt = wp.forwardsToStmt(); this.addField(<RecordField>stmt, "W") }); dd.direct.asIEnumerable.forEach(e => { if (this.declsToLibrary.indexOf(e) >= 0 && this.collectionOfRecords.indexOf(e) < 0) this.collectionOfRecords.push(e); }); }); } // these are all derived from dd private rewriteFields: RecordField[] = []; private fieldModes: string[] = []; private rewriteGlobals: Decl[] = []; private globalModes: string[] = []; private globalThings: string[] = []; private rewriteProperties: IProperty[] = []; private rewritePropertiesExpr: Expr[] = []; private collectionOfRecords: RecordDef[] = []; private getRecordName(prop: IProperty): string { var rd = <RecordDef>prop.parentKind.getRecord(); if (rd && this.declsToLibrary.indexOf(rd) >= 0) { return rd.getName() + " " + prop.getName(); } return null; } // this should be part of accessor. public getAccessorName(e: Expr, mode: string): string { if (e.referencedData()) { var glob = e.referencedData(); if (this.declsToLibrary.indexOf(e.referencedData()) >= 0) { return (mode == "R" ? "" : "set ") + glob.getName(); } } else if (e.referencedRecordField()) { var field = e.referencedRecordField(); var recordDef = field.def(); if (this.declsToLibrary.indexOf(recordDef) >= 0) { return (mode == "R" ? "" : "set ") + field.getName(); } } else if (e.calledProp()) { var c = <Call>e; if (e.calledProp() instanceof RecordDef) { var rd2 = <RecordDef>c.prop(); if (this.declsToLibrary.indexOf(rd2) >= 0) return rd2.getName() + (mode == "E" ? " collection" : ""); } else { return this.getRecordName(c.prop()); } } return null; } private getName(name: string, mode: string): string { return (mode == "W" ? "set " : "") + name; } // either glob nonnull iff field null private makeActionFromGlobOrField(thing: string, glob: Decl, field: RecordField, mode: string): Action { var writer = new TokenWriter(); writer.keyword("action").id(this.getName(glob ? glob.getName() : field.getName(), mode)); writer.op("("); if (!glob) { writer.id("r").op(":").kind(this.theApp, field.def().entryKind); if (mode == "W") writer.op(","); } if (mode == "W") { writer.id("val").op(":").kind(this.theApp, glob ? glob.getKind() : field.dataKind) } writer.op(")"); if (mode == "R") { writer.keyword("returns").op("(").id("val").op(":").kind(this.theApp, glob ? glob.getKind() : field.dataKind).op(")"); } writer.op("{"); if (mode == "R") { writer.id("val").op(":="); } if (glob) { writer.id(thing); } else { writer.id("r"); } writer.op("→").id(glob ? glob.getName() : field.getName()); if (mode == "W") { writer.op(":=").id("val"); } writer.op("}"); return <Action> Parser.parseDecl(writer.finalize()); } // TODO: we need to generate different names if we have the same property private makeActionFromProperty(prop: IProperty, expr: Expr): Action { var record = prop.parentKind.getRecord(); // property return value? // property arguments var writer = new TokenWriter(); writer.keyword("action"); // put in the parameters var name = this.getRecordName(prop); if (name == null) name = prop.getName(); writer.id(name).op("("); var parms = prop.getParameters(); var first = true; if (expr.getKind() instanceof RecordEntryKind) { writer.id("r").op(":").id(record.entryKind.getName()); first = false; } // always skip the implicit this var i = 1; while (i < parms.length) { if (!first) writer.op(","); var p = parms[i]; writer.id(p.getName()).op(":").kind(this.theApp, p.getKind()); i++; } writer.op(")"); var res = prop.getResult(); if (res) { writer.keyword("returns").op("("); writer.id("res").op(":").kind(this.theApp, res.getKind()); writer.op(")"); } writer.op("{"); // now call the property on record if (res) { writer.id("res").op(":="); } if (expr.getKind() instanceof RecordEntryKind) { writer.id("r"); } else { writer.id(record.thingSetKindName()).op("→").id(record.getName()); } writer.op("→").id(prop.getName()); i = 1; if (i < parms.length && parms.length > 0) { writer.op("("); var first = true; while (i < parms.length) { if (!first) writer.op(","); writer.id(parms[i].getName()); i++; first = false; } writer.op(")"); } writer.op("}"); return <Action> Parser.parseDecl(writer.finalize()); } private collectionTemplate = "action $NAME_collection() returns(coll: Collection[ * $ENTRY]) { " + "$coll := records→$NAME→create_collection; " + "foreach e in records→$NAME where true do { $coll→add($e); } " + "}"; private makeCollectionAccessor(rd: RecordDef): Action { var text = this.collectionTemplate; text = text.replace(/\$NAME/g, Lexer.quoteId(rd.getName())) .replace(/\$ENTRY/g, Lexer.quoteId(rd.entryKind.getName())); return <Action> Parser.parseDecl(text); } public getAccessorActions(): Action[] { var actions: Action[] = []; for (var i = 0; i < this.rewriteGlobals.length; i++) { for (var j = 0; j < this.globalModes[i].length; j++) { actions.push(this.makeActionFromGlobOrField(this.globalThings[i], this.rewriteGlobals[i], null, this.globalModes[i][j])); } } for (var i = 0; i < this.rewriteFields.length; i++) { for (var j = 0; j < this.fieldModes[i].length; j++) { actions.push(this.makeActionFromGlobOrField(null, null, this.rewriteFields[i], this.fieldModes[i][j])); } } this.rewriteProperties.forEach((p, i) => actions.push(this.makeActionFromProperty(p, this.rewritePropertiesExpr[i]))); this.collectionOfRecords.forEach(r => actions.push(this.makeCollectionAccessor(r))); return actions; } private addField(field: RecordField, mode: string) { var recordDef = field.def(); if (this.declsToLibrary.indexOf(recordDef) >= 0) { var index = this.rewriteFields.indexOf(field); if (index < 0) { this.rewriteFields.push(field); this.fieldModes.push(mode); } else { if (this.fieldModes[index].indexOf(mode) < 0) { this.fieldModes[index] += mode; } } } } private addGlobal(decl: Decl, mode: string) { if (this.declsToLibrary.indexOf(decl) >= 0 && decl instanceof GlobalDef) { var glob = <GlobalDef>decl; var index = this.rewriteGlobals.indexOf(glob); if (index < 0) { this.rewriteGlobals.push(glob); this.globalModes.push(mode); this.globalThings.push(glob.thingSetKindName()); } else { if (this.globalModes[index].indexOf(mode) < 0) { this.globalModes[index] += mode; } } } } private addProperty(p: IProperty, e: Expr) { var rd = p.parentKind.getRecord(); if (rd && this.declsToLibrary.indexOf(rd) >= 0 && this.rewriteProperties.indexOf(p) < 0) { this.rewriteProperties.push(p); this.rewritePropertiesExpr.push(e); } } } // rewrite a kind, which may depend on types moved to the library class RewriteKind { // two modes for rewriting // 1. declsToMove.length > 0 && replaceTarget==false // 2. declsToMove.length == 0 && replaceTarget==true constructor(public targetLibrary: LibraryRef, public declsToMove: Decl[], public replaceTarget: boolean) { } public rewriteKind(k: Kind): Kind { if (k.getRecord()) { var rec = k.getRecord(); if (this.declsToMove.indexOf(rec) >= 0) { return this.targetLibrary.getAbstractKind(k.getName()); } } else if (k instanceof UserActionKind) { var act = (<UserActionKind>k).userAction; if (this.declsToMove.indexOf(act) >= 0) { // nothing to do, since all dependent types are in downwards closure } else { act.getParameters().forEach(p => { p._kind = this.rewriteKind(p.getKind()) }); } } else if (k instanceof LibraryRefAbstractKind) { // we are taking a dependence on a library var absKind = <LibraryRefAbstractKind>k; var lib = absKind.parentLibrary(); if (this.replaceTarget && lib == this.targetLibrary) { return new UnresolvedKind(absKind.getName()); } } else if (k instanceof ParametricKind) { var pk = <ParametricKind>k; pk.parameters.forEach((p, i) => pk.parameters[i] = this.rewriteKind(pk.parameters[i])); } else if (k instanceof ActionKind) { var params = (<ActionKind>k).getInParameters().concat((<ActionKind>k).getOutParameters()); params.forEach(p => { p._kind = this.rewriteKind(p.getKind()) }); } return k; } } // for removing reference to target library // TODO: we may want to create a "rewriting visitor" base class at some point class RemoveLibraryReference extends NodeVisitor { constructor(public targetLibrary: LibraryRef) { super(); this.rewriteKind = new RewriteKind(this.targetLibrary, [], true); } private rewriteKind: RewriteKind; private lastExprHolder: ExprHolder; visitAstNode(n: AstNode) { this.visitChildren(n); return null; } visitExprHolder(n: ExprHolder) { this.lastExprHolder = n; if (n.parsed) this.dispatch(n.parsed); return null; } visitAction(n: Action) { super.visitAction(n); n.getInParameters().concat(n.getOutParameters()). forEach((p) => { p.local.setKind(this.rewriteKind.rewriteKind(p.local.getKind())); }); } visitGlobalDef(n: GlobalDef) { n.setKind(this.rewriteKind.rewriteKind(n.getKind())); } visitRecordDef(n: RecordDef) { n.getFields().forEach(f => { f.dataKind = this.rewriteKind.rewriteKind(f.dataKind) }); } // are we calling visitCall(n: Call) { n.args.forEach(e => { this.dispatch(e); }); var prop = n.prop(); var thingref = <ThingRef>n.args[0]; if (prop && prop.forwardsTo() instanceof LibraryRefAction) { var lra = <LibraryRefAction>prop.forwardsTo(); if (lra.parentLibrary() == this.targetLibrary) { // TODO: this is pretty ugly and repeated (encapsulate, if you dare) var subcall = <Call>n.args[0]; var tokens = this.lastExprHolder.tokens; var leftmost = getLeftmost(n.args[0]); var leftIdx = tokens.indexOf(leftmost); var rightIdx = tokens.indexOf(subcall.propRef); if (!(lra instanceof LibExtensionAction) && leftmost instanceof ThingRef) { var writer = new TokenWriter(); writer.keyword("code"); var newExprHolder = Parser.parseExprHolder(writer.finalize()); tokens.spliceArr(leftIdx, rightIdx - leftIdx + 1, newExprHolder.tokens); } } } } } class RewriteApp extends NodeVisitor { constructor(public targetLibrary: LibraryRef, public libActions: Decl[], public acc: CreateAccessors) { super(); this.rewriteKind = new RewriteKind(this.targetLibrary, this.acc.declsToLibrary, false); } private lastExprHolder: ExprHolder = null; private mode: string = ""; private rewriteKind: RewriteKind; visitExprHolder(n: ExprHolder) { this.lastExprHolder = n; this.mode = "R"; if (n.parsed) this.dispatch(n.parsed); return null; } visitForeach(n: Foreach) { if (n.collection.parsed) { this.mode = "E"; this.lastExprHolder = n.collection; this.dispatch(n.collection.parsed); } [<AstNode> n.conditions, n.body].forEach(c => c.accept(this)); } visitAstNode(n: AstNode) { this.visitChildren(n); return null; } // only rewrite actions in app visitAction(n: Action) { if (this.libActions.indexOf(n) < 0) { super.visitAction(n); n.getInParameters().concat(n.getOutParameters()). forEach((p) => this.rewriteActionParameter(p)); } } rewriteActionParameter(n: ActionParameter) { n.local.setKind(this.rewriteKind.rewriteKind(n.local.getKind())); } // for globals and records remaining in the app, we may need to rewrite // some of their reference types, if those moved to the library visitGlobalDef(n: GlobalDef) { if (this.acc.declsToLibrary.indexOf(n) < 0) { n.setKind(this.rewriteKind.rewriteKind(n.getKind())); } } visitRecordDef(n: RecordDef) { if (this.acc.declsToLibrary.indexOf(n) < 0) { // for a record still in the app, check it fields to see what needs to be written n.getFields().forEach(f => { f.dataKind = this.rewriteKind.rewriteKind(f.dataKind) }); } } // helper method for rewriting call rewriteThingRef(t: ThingRef) { var tokens = this.lastExprHolder.tokens; var idx = tokens.indexOf(t); var writer = new TokenWriter(); this.targetLibrary.writeRef(writer); var newExprHolder = Parser.parseExprHolder(writer.finalize()); this.lastExprHolder.tokens.spliceArr(idx, 1, newExprHolder.tokens); } // when rewriting a call, we need to be careful to rewrite bottom up, // as calls can be nested under calls. we also need to track mode, as // done in DirectAccessFinder visitCall(n: Call) { var prop = n.prop(); if (!prop) return; // assignment guaranteed to be outermost in token stream because assignments aren't expressions if (prop == api.core.AssignmentProp) { var lhs = n.args[0].flatten(api.core.TupleProp); lhs.forEach(((e) => { this.mode = "W"; // this trick works because AssignmentProp is not nested even though calls are this.dispatch(e); })); this.mode = "R"; var rhs = n.args[1]; this.dispatch(rhs); // TODO: need to wait for Michal in order to support lhs.length > 1 if (lhs.length == 1) { var oneLHS = <Call>lhs[0]; // does the LHS require a rewrite? var accessor = this.acc.getAccessorName(oneLHS, "W"); if (accessor != null) { var writer = new TokenWriter(); var tokens = this.lastExprHolder.tokens; if (oneLHS.referencedRecordField()) { var oneLHStok = tokens.filter(t => t == oneLHS.propRef)[0] var oneLHSidx = tokens.indexOf(oneLHStok); tokens.slice(0, oneLHSidx).forEach(t => t.writeTo(writer)); } else { this.targetLibrary.writeRef(writer); } writer.op("→").id(accessor).op("("); var assign = tokens.filter(t => t.getOperator() == ":=")[0] var idx = tokens.indexOf(assign); tokens.slice(idx + 1, tokens.length).forEach(t => t.writeTo(writer)); writer.op(")"); var newExprHolder = Parser.parseExprHolder(writer.finalize()); // replacement OK here because we're at top level (otherwise, need to splice) this.lastExprHolder.tokens = newExprHolder.tokens; } } } else if (n.referencedData() || n.referencedRecordField()) { // remember what was set up one level in AST (by Call/Assignment) var mode = this.mode; this.mode = "R"; n.args.forEach(e => this.dispatch(e)); // read of global or field // do rewriting on Call via PropertyRef of Call, which is a Token var accessor = this.acc.getAccessorName(n, mode); if (accessor != null && mode != "W") { n.propRef.data = accessor; if (n.referencedData()) { this.rewriteThingRef(<ThingRef>n.args[0]); } else { // use extension syntax because record will be first arg to accessor (no library reference needed) n.propRef.prop = null; } } } else if (prop instanceof RecordDef) { if (this.mode == "E") { var accessor = this.acc.getAccessorName(n, "E"); if (accessor != null) { var tokens = this.lastExprHolder.tokens; var leftmost = getLeftmost(n); var leftIdx = tokens.indexOf(leftmost); var rightIdx = tokens.indexOf(n.propRef); // create the library thingref var writer = new TokenWriter(); this.targetLibrary.writeRef(writer).op("→").id(accessor); var newExprHolder = Parser.parseExprHolder(writer.finalize()); tokens.spliceArr(leftIdx, rightIdx - leftIdx + 1, newExprHolder.tokens); } } } else if (prop && (prop.forwardsTo() instanceof Action || prop instanceof ExtensionProperty)) { this.mode = "R"; n.args.forEach(e => this.dispatch(e)); var callee = <Action>prop.forwardsTo(); if (callee && this.libActions.indexOf(callee) >= 0) { this.rewriteThingRef(<ThingRef>n.args[0]); } else { callee = (<ExtensionProperty>prop).shortcutTo; if (this.libActions.indexOf(callee) >= 0) { // TODO: finish this case } } } else { n.args.forEach(e => { this.mode = "R"; this.dispatch(e); }); var accessor = this.acc.getAccessorName(n, ""); if (accessor != null && prop) { n.propRef.data = accessor; n.propRef.prop = null; var kind = prop.parentKind; if (kind instanceof RecordDefKind) { var rd = (<RecordDefKind>kind).getRecord(); if (rd) { var subcall = <Call>n.args[0]; var leftmost = getLeftmost(subcall); // TODO: are we sure about thingref check??? if (leftmost instanceof ThingRef) { // replace the subcall by thingref // identify the token subsequence associated with subcall var tokens = this.lastExprHolder.tokens; var leftIdx = tokens.indexOf(leftmost); var rightIdx = tokens.indexOf(subcall.propRef); // create the library thingref var writer = new TokenWriter(); this.targetLibrary.writeRef(writer); var newExprHolder = Parser.parseExprHolder(writer.finalize()); // replace the subcall sequence with the library thingref tokens.spliceArr(leftIdx, rightIdx - leftIdx + 1, newExprHolder.tokens); } else { // it's a local variable or parameter, } } } else { // nothing to do here } } } return null; } performRewrite(n: AstNode) { this.dispatch(n); } } // given a record or record field R, find all the other user defined types reachable from R class UserDefinedTypeFinder extends NodeVisitor { private recurse: boolean = false; decls: Decl[] = []; visitGlobalDef(n: GlobalDef) { this.visitKind(n.getKind(), this.recurse); } visitLocalDef(n: LocalDef) { this.visitKind(n.getKind(), this.recurse); } visitRecordDef(r: RecordDef) { if (this.decls.indexOf(r) < 0) { this.decls.push(r); if (this.recurse) { r.values.fields().concat(r.keys.fields()).forEach((f) => { this.visitRecordField(f); }); } } } visitRecordField(n: RecordField) { this.visitKind(n.dataKind, this.recurse); } public visitKind(k: Kind, recurse: boolean) { this.recurse = recurse; if (k.isUserDefined()) { if (k.getRecord()) this.visitRecordDef(k.getRecord()); else if (k instanceof UserActionKind) { var act = (<UserActionKind>k).userAction; if (this.decls.indexOf(act) < 0) { this.decls.push(act); if (recurse) { act.getParameters().forEach(p => this.visitKind(p.getKind(), recurse)); } } } else if (k instanceof LibraryRefAbstractKind) { // we are taking a dependence on a library var lib = (<LibraryRefAbstractKind>k).parentLibrary(); if (this.decls.indexOf(lib) < 0) { this.decls.push(lib); } } else if (k instanceof ParametricKind) { if (recurse) { var pk = <ParametricKind>k; var i = 0; while (i < pk.getParameterCount()) { this.visitKind(pk.getParameter(i), recurse); i++; } } } else if (k instanceof ActionKind) { if (recurse) { var params = (<ActionKind>k).getInParameters().concat((<ActionKind>k).getInParameters()); params.forEach(p => this.visitKind(p.getKind(), recurse)); } } else { // Question: do we need to recurse over SimpleProperties and their param/return types // Answer: depends if we can reach a userdefined type from a Simple Property, which I // don't think is possible. } } } public traverse(d: AstNode, recurse: boolean) { this.recurse = recurse; this.dispatch(d); } } export class DeclAndDepsManager { private cache: DeclAndDeps[] = []; private last: DeclAndDeps = null; public resetCache() { this.cache = []; this.last = null; } public invalidate() { this.cache.forEach(dd => dd.reset()); } private getFromCache(d: Decl): DeclAndDeps { if (this.last != null && this.last.decl == d) { return this.last; } else { var filter = this.cache.filter(dd => dd.decl == d); if (filter.length > 0) { this.last = filter[0]; return this.last; } else return null; } } public remove(dd: DeclAndDeps) { this.last = null; var idx = this.cache.indexOf(dd); if (idx >= 0) { this.cache.splice(idx); } } public getter(decl: Decl): DeclAndDeps { Util.assert(decl != null); var res = this.getFromCache(decl); if (res == null) { res = new DeclAndDeps(this); res.decl = decl; this.cache.push(res); } return res; } public getAll(): DeclAndDeps[] { return this.cache; } } // wrap decl in the AST to keep track of its dependences export class DeclAndDeps { private manager: DeclAndDepsManager; constructor(m: DeclAndDepsManager) { this.manager = m; } public decl: Decl = null; public serialized: string; // remember the decl for restoring later public direct: DirectAccessFinder = null; // which actions are called by decl? private actions: DeclAndDeps[] = null; // types directly referenced by decl private otherDecls: DeclAndDeps[] = []; // decls for which this action actually reads/write a field or property private accessedTypes: DeclAndDeps[] = []; private accessedGlobals: DeclAndDeps[] = []; private transitiveClosure: DeclAndDeps[] = null; public reset() { this.actions = null; this.serialized = null; this.otherDecls = []; this.direct = null; this.accessedGlobals = []; this.accessedTypes = []; this.transitiveClosure = []; } public getActions(): DeclAndDeps[] { this.fillDeclDependencies(); return this.actions; } public getOthers(): DeclAndDeps[] { this.fillDeclDependencies(); return this.otherDecls; } public getAllDirectAccesses(): DeclAndDeps[] { this.fillDeclDependencies(); if (this.decl instanceof Action) return this.accessedTypes.concat(this.accessedGlobals).concat(this.getActions()); else return this.getOthers(); } public getTransitiveClosure(): DeclAndDeps[] { this.fillDeclDependencies(); if (!this.transitiveClosure) { this.transitiveClosure = []; DeclAndDeps.computeClosure([this], [], this.transitiveClosure); } return this.transitiveClosure; } // for user selection private include: boolean = false; public setInclude(b: boolean) { this.include = b; } public getInclude(): boolean { return this.include; } public count: number; // for ranking the declarations in order of suitability for library public numberDirectDeclsToMove: number; static rateTargetAgainstDecls(pending: DeclAndDeps[], tgt: DeclAndDeps) { tgt.numberDirectDeclsToMove = 0; tgt.getAllDirectAccesses().filter(dd => !(dd.decl instanceof LibraryRef)).forEach((t) => { if (pending.indexOf(t) >= 0) tgt.numberDirectDeclsToMove++; }); } static compareSize(d1: DeclAndDeps, d2: DeclAndDeps): number { var len1 = d1.getTransitiveClosure().length; var len2 = d2.getTransitiveClosure().length; return len1 - len2; } private fillDeclDependencies() { if (this.actions != null) return; var directDecls: Decl[] = []; function add(decl: Decl) { if (directDecls.indexOf(decl) < 0) directDecls.push(decl); } function processDeclDirect(decl: Decl) { // local defs aren't moveable decls if (!(decl instanceof LocalDef)) add(decl); // now, find the types directly accessed var finder = new UserDefinedTypeFinder(); finder.traverse(decl, false); finder.decls.forEach(d => add(d)); } var finder = new DirectAccessFinder(); finder.traverse(this.decl); this.direct = finder; finder.referencedLibraries.forEach(l => add(l)); if (this.decl instanceof Action) { this.actions = finder.calledActions.map(a => this.manager.getter(a)); finder.readGlobals.concat(finder.writtenGlobals).forEach(g => { var ng = this.manager.getter(g); if (this.accessedGlobals.indexOf(ng) < 0) this.accessedGlobals.push(ng); processDeclDirect(g); }); finder.inParams.concat(finder.outParams).forEach(processDeclDirect); finder.readProps.concat(finder.readFields).concat(finder.writtenFields).forEach(p => { var rd = p.parentKind.getRecord(); if (rd) { var newOne = this.manager.getter(rd); if (this.accessedTypes.indexOf(newOne) < 0) this.accessedTypes.push(newOne); } }); } else { this.actions = []; finder.referencedRecords.forEach(processDeclDirect); } this.otherDecls = directDecls.map(a => this.manager.getter(a)); } public static computeClosure(roots: DeclAndDeps[], alreadyIn: DeclAndDeps[], newOnes: DeclAndDeps[]) { var add = (dd2: DeclAndDeps) => { if (roots.indexOf(dd2) < 0 && alreadyIn.indexOf(dd2) < 0 && newOnes.indexOf(dd2) < 0) { newOnes.push(dd2); return true; } else { return false; } } var recurseNotAction = (r: DeclAndDeps) => { if (add(r)) { var finder = new UserDefinedTypeFinder(); finder.traverse(r.decl, true); finder.decls.forEach(d => add(r.manager.getter(d))); } } roots.forEach(dd => { if (dd.decl instanceof Action) { var closure = new CallGraphClosure(dd); closure.allActions.forEach((a) => { if (add(a)) a.getOthers().forEach(recurseNotAction); }); } else { recurseNotAction(dd); } dd.getOthers().forEach(recurseNotAction); }); } } class CallGraphClosure { constructor(action: DeclAndDeps) { var wl: DeclAndDeps[] = action.getActions().map(x=> x); while (wl.length > 0) { var a = wl.pop(); this.allActions.push(a); a.getActions().forEach(b => { if (this.allActions.indexOf(b) < 0 && wl.indexOf(b) < 0) wl.push(b) }); } } public allActions: DeclAndDeps[] = []; } function getLeftmost(e: Expr): Expr { if (e instanceof Call) { return getLeftmost((<Call>e).args[0]); } else { return e; } } // the stuff below here should be generically useful for lots of other // refactoring and analyses that need to find out what is referenced by // a declaration (action, global, record, etc.) // given an action A, find all the other top-level entities referenced directly by A export class DirectAccessFinder extends NodeVisitor { referencedLibraries: LibraryRef[] = []; calledActions: Action[] = []; inParams: LocalDef[] = []; outParams: LocalDef[] = []; readGlobals: Decl[] = []; writtenGlobals: Decl[] = []; readFields: IProperty[] = []; writtenFields: IProperty[] = []; readProps: IProperty[] = []; readPropsWhat: Expr[] = []; referencedRecords: RecordDef[] = []; asIEnumerable: RecordDef[] = []; addDecl(l: Decl, lst: Decl[]) { if (lst.indexOf(l) < 0) lst.push(l); } addField(l: IProperty, lst: IProperty[]) { if (lst.indexOf(l) < 0) lst.push(l); } addProp(l: IProperty, e: Expr) { if (this.readProps.indexOf(l) < 0) { this.readProps.push(l); this.readPropsWhat.push(e); } } private getGlobal(e: AstNode) { if (e instanceof Call) { var prop = (<Call>e).prop(); if (prop instanceof GlobalDef || prop instanceof RecordDef) return <PropertyDecl><any>prop; } return null; } visitAstNode(n: AstNode) { this.visitChildren(n); return null; } visitAction(n: Action) { n.getInParameters().forEach((p) => this.addDecl(p.local, this.inParams)); n.getOutParameters().forEach((p) => this.addDecl(p.local, this.outParams)); super.visitAction(n); } visitGlobalDef(n: GlobalDef) { var finder = new UserDefinedTypeFinder(); finder.traverse(n, false); finder.decls.forEach(t => this.addDecl(t, this.referencedRecords)); } visitRecordDef(r: RecordDef) { var finder = new UserDefinedTypeFinder(); r.values.fields().concat(r.keys.fields()).forEach((f) => { finder.traverse(f, false); }); finder.decls.forEach(t => this.addDecl(t, this.referencedRecords)); } visitForeach(n: Foreach) { if (n.collection.parsed) { this.mode = "E"; this.dispatch(n.collection.parsed); } [<AstNode> n.conditions, n.body].forEach(c => c.accept(this)); } private mode: string = ""; visitCall(n: Call) { var prop = n.prop(); if (prop == api.core.AssignmentProp) { n.args[0].flatten(api.core.TupleProp).forEach((e) => { this.mode = "W"; var g = this.getGlobal(e); if (g && this.writtenGlobals.indexOf(g) < 0) this.addDecl(g, this.writtenGlobals); else this.dispatch(e); }); this.mode = "R"; this.dispatch(n.args[1]); } else if (n.referencedRecordField() || n.referencedData()) { if (n.referencedRecordField()) { this.addField(n.referencedRecordField().asProperty(), this.mode == "R" ? this.readFields : this.writtenFields); } else { this.addDecl(n.referencedData(), this.mode == "R" ? this.readGlobals : this.writtenGlobals); } } else if (prop instanceof RecordDef) { // direct use of (built-in property of) a table/index if (this.mode == "E") { this.addDecl(<RecordDef>prop, this.asIEnumerable); } this.addDecl(<RecordDef>prop, this.readGlobals); } else if (prop.forwardsTo() instanceof Action || prop instanceof ExtensionProperty) { var act = prop.forwardsTo() ? <Action> prop.forwardsTo() : (<ExtensionProperty>prop).shortcutTo; var lib = act.parentLibrary(); if (lib && !lib.isThis()) { if (this.referencedLibraries.indexOf(lib) < 0) this.referencedLibraries.push(lib); } else { if (this.calledActions.indexOf(act) < 0) this.calledActions.push(act); } } else if (prop.parentKind.getRecord()) { this.addProp(prop, getLeftmost(n)); } else if (prop.parentKind instanceof UserActionKind) { // we have a run call (look for dependence on a callback) var act = (<UserActionKind>(prop.parentKind)).userAction if (this.calledActions.indexOf(act) < 0) this.calledActions.push(act); } // recurse and collect from arguments if (prop != api.core.AssignmentProp) { n.args.forEach(e => { this.mode = "R"; this.dispatch(e) }); } } visitExprHolder(n: ExprHolder) { if (n.parsed) { this.mode = "R"; this.dispatch(n.parsed); } return null; } traverse(node: AstNode) { this.dispatch(node); } } }
the_stack
import { isFunction, isObject, keysOf, hasOwn, convertMapToObject, isArguments, handleError, checkError, } from "./utilities"; import canonicalStringify from "./stringify"; import { fromJSONValueHelper } from "./utils/fromJSONValueHelper"; import { adjustTypesFromJSONValue } from "./utils/adjustTypesFromJSONValue"; import { toJSONValueHelper } from "./utils/toJSONValueHelper"; import { adjustTypesToJSONValue } from "./utils/adjustTypesToJSONValue"; import { builtinConverters } from "./utils/builtinConverters"; import { ObjectId } from "./objectid"; export class EJSON { static customTypes = new Map(); // Add a custom type, using a method of your choice to get to and // from a basic JSON-able representation. The factory argument // is a function of JSON-able --> your object // The type you add must have: // - A toJSONValue() method, so that Meteor can serialize it // - a typeName() method, to show how to look it up in our type table. // It is okay if these methods are monkey-patched on. // EJSON.clone will use toJSONValue and the given factory to produce // a clone, but you may specify a method clone() that will be // used instead. // Similarly, EJSON.equals will use toJSONValue to make comparisons, // but you may provide a method equals() instead. /** * @summary Add a custom datatype to EJSON. * @locus Anywhere * @param {String} name A tag for your custom type; must be unique among * custom data types defined in your project, and must * match the result of your type's `typeName` method. * @param {Function} factory A function that deserializes a JSON-compatible * value into an instance of your type. This should * match the serialization performed by your * type's `toJSONValue` method. */ static addType(name, factory) { if (EJSON.customTypes.has(name)) { throw new Error(`Type ${name} already present`); } EJSON.customTypes.set(name, factory); } static _isCustomType(obj) { return ( obj && isFunction(obj.toJSONValue) && isFunction(obj.typeName) && EJSON.customTypes.has(obj.typeName()) ); } static _getTypes(isOriginal = false) { return isOriginal ? EJSON.customTypes : convertMapToObject(EJSON.customTypes); } static _getConverters = () => builtinConverters; static _adjustTypesToJSONValue = adjustTypesToJSONValue; /** * @summary Serialize an EJSON-compatible value into its plain JSON * representation. * @locus Anywhere * @param {EJSON} val A value to serialize to plain JSON. */ static toJSONValue(item) { const changed = toJSONValueHelper(item); if (changed !== undefined) { return changed; } let newItem = item; if (isObject(item)) { newItem = EJSON.clone(item); adjustTypesToJSONValue(newItem); } return newItem; } static _adjustTypesFromJSONValue = adjustTypesFromJSONValue; /** * @summary Deserialize an EJSON value from its plain JSON representation. * @locus Anywhere * @param {JSONCompatible} val A value to deserialize into EJSON. */ static fromJSONValue(item) { let changed = fromJSONValueHelper(item); if (changed === item && isObject(item)) { changed = EJSON.clone(item); adjustTypesFromJSONValue(changed); } return changed; } /** * @summary Serialize a value to a string. For EJSON values, the serialization * fully represents the value. For non-EJSON values, serializes the * same way as `JSON.stringify`. * @locus Anywhere * @param {EJSON} val A value to stringify. * @param {Object} [options] * @param {Boolean | Integer | String} options.indent Indents objects and * arrays for easy readability. When `true`, indents by 2 spaces; when an * integer, indents by that number of spaces; and when a string, uses the * string as the indentation pattern. * @param {Boolean} options.canonical When `true`, stringifies keys in an * object in sorted order. */ static stringify(item, options?) { try { let serialized; const json = EJSON.toJSONValue(item); if (options && (options.canonical || options.indent)) { serialized = canonicalStringify(json, options); } else { serialized = JSON.stringify(json); } return serialized; } catch (error) { const isMaxStack = checkError.maxStack(error.message); if (isMaxStack) { throw new Error("Converting circular structure to JSON"); } throw error; } } /** * @summary Parse a string into an EJSON value. Throws an error if the string * is not valid EJSON. * @locus Anywhere * @param {String} str A string to parse into an EJSON value. */ static parse(item) { if (typeof item !== "string") { throw new Error("EJSON.parse argument should be a string"); } return EJSON.fromJSONValue(JSON.parse(item)); } /** * @summary Returns true if `x` is a buffer of binary data, as returned from * [`EJSON.newBinary`](#ejson_new_binary). * @param {Object} x The variable to check. * @locus Anywhere */ static isBinary(obj) { return !!( (typeof Uint8Array !== "undefined" && obj instanceof Uint8Array) || (obj && obj.$Uint8ArrayPolyfill) ); } /** * @summary Return true if `a` and `b` are equal to each other. Return false * otherwise. Uses the `equals` method on `a` if present, otherwise * performs a deep comparison. * @locus Anywhere * @param {EJSON} a * @param {EJSON} b * @param {Object} [options] * @param {Boolean} options.keyOrderSensitive Compare in key sensitive order, * if supported by the JavaScript implementation. For example, `{a: 1, b: 2}` * is equal to `{b: 2, a: 1}` only when `keyOrderSensitive` is `false`. The * default is `false`. */ static equals(a, b, options?) { let i; const keyOrderSensitive = !!(options && options.keyOrderSensitive); if (a === b) { return true; } // This differs from the IEEE spec for NaN equality, b/c we don't want // anything ever with a NaN to be poisoned from becoming equal to anything. if (Number.isNaN(a) && Number.isNaN(b)) { return true; } // if either one is falsy, they'd have to be === to be equal if (!a || !b) { return false; } if (!(isObject(a) && isObject(b))) { return false; } if (a instanceof Date && b instanceof Date) { return a.valueOf() === b.valueOf(); } if (EJSON.isBinary(a) && EJSON.isBinary(b)) { if (a.length !== b.length) { return false; } for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } if (isFunction(a.equals)) { return a.equals(b, options); } if (isFunction(b.equals)) { return b.equals(a, options); } if (a instanceof Array) { if (!(b instanceof Array)) { return false; } if (a.length !== b.length) { return false; } for (i = 0; i < a.length; i++) { if (!EJSON.equals(a[i], b[i], options)) { return false; } } return true; } // fallback for custom types that don't implement their own equals let sum = 0; if (EJSON._isCustomType(a)) sum++; if (EJSON._isCustomType(b)) sum++; switch (sum) { case 1: return false; case 2: return EJSON.equals(EJSON.toJSONValue(a), EJSON.toJSONValue(b)); default: // Do nothing } // fall back to structural equality of objects let ret; const aKeys = keysOf(a); const bKeys = keysOf(b); if (keyOrderSensitive) { i = 0; ret = aKeys.every((key) => { if (i >= bKeys.length) { return false; } if (key !== bKeys[i]) { return false; } if (!EJSON.equals(a[key], b[bKeys[i]], options)) { return false; } i++; return true; }); } else { i = 0; ret = aKeys.every((key) => { if (!hasOwn(b, key)) { return false; } if (!EJSON.equals(a[key], b[key], options)) { return false; } i++; return true; }); } return ret && i === bKeys.length; } /** * @summary Return a deep copy of `val`. * @locus Anywhere * @param {EJSON} val A value to copy. */ static clone(v) { let ret; if (!isObject(v)) { return v; } if (v === null) { return null; // null has typeof "object" } if (v instanceof Date) { return new Date(v.getTime()); } // RegExps are not really EJSON elements (eg we don't define a serialization // for them), but they're immutable anyway, so we can support them in clone. if (v instanceof RegExp) { return v; } if (ObjectId.isValid(v)) { return v; } if (EJSON.isBinary(v)) { ret = EJSON.newBinary(v.length); for (let i = 0; i < v.length; i++) { ret[i] = v[i]; } return ret; } if (Array.isArray(v)) { return v.map(EJSON.clone); } if (isArguments(v)) { return Array.from(v).map(EJSON.clone); } // handle general user-defined typed Objects if they have a clone method if (isFunction(v.clone)) { return v.clone(); } // handle other custom types if (EJSON._isCustomType(v)) { return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(v))); } // handle other objects ret = {}; keysOf(v).forEach((key) => { ret[key] = EJSON.clone(v[key]); }); return ret; } /** * @summary Allocate a new buffer of binary data that EJSON can serialize. * @locus Anywhere * @param {Number} size The number of bytes of binary data to allocate. */ static newBinary(len) { if ( typeof Uint8Array === "undefined" || typeof ArrayBuffer === "undefined" ) { const ret: any = []; for (let i = 0; i < len; i++) { ret.push(0); } ret.$Uint8ArrayPolyfill = true; return ret; } return new Uint8Array(new ArrayBuffer(len)); } }
the_stack
module TDev.AST.Json { export class NodeVisitor { /// visitor methods based on nodeType to override in specialized visitors public visit_exprHolder(holder: JExprHolder): any { return this.visit_node(holder); } public visit_stringLiteral(lit: JStringLiteral): any { return this.visit_expr(lit); } public visit_numberLiteral(lit: JNumberLiteral): any { return this.visit_expr(lit); } public visit_booleanLiteral(lit: JBooleanLiteral): any { return this.visit_expr(lit); } public visit_call(call: JCall): any { return this.visit_expr(call); } public visit_localRef(local: JLocalRef): any { return this.visit_expr(local); } public visit_exprStmt(node: JExprStmt): any { return this.visit_stmt(node); } public visit_inlineAction(action: JInlineAction): any { return this.visit_node(action); } public visit_inlineActions(actions: JInlineActions): any { return this.visit_exprStmt(actions); } public visit_boxed(boxed: JBoxed): any { return this.visit_stmt(boxed); } public visit_singletonRef(singleton: JSingletonRef): any { return this.visit_expr(singleton); } public visit_if(node: JIf): any { return this.visit_stmt(node); } public visit_propertyRef(property: JPropertyRef): any { return this.visit_token(property); } public visit_localDef(local: JLocalDef): any { return this.visit_node(local); } public visit_action(action: JAction): any { return this.visit_actionBase(action); } public visit_comment(comment: JComment): any { return this.visit_stmt(comment); } public visit_operator(op: JOperator): any { return this.visit_token(op); } public visit_while(stmt: JWhile): any { return this.visit_stmt(stmt); } public visit_for(stmt: JFor): any { return this.visit_stmt(stmt); } public visit_foreach(stmt: JForeach): any { return this.visit_stmt(stmt); } public visit_where(clause: JWhere): any { return this.visit_condition(clause); } public visit_typeRef(type: JTypeRef): any { return null; } public visit_placeholder(p: JPlaceholder): any { return this.visit_expr(p); } public visit_page(p: JPage): any { return this.visit_actionBase(p); } public visit_event(e: JEvent): any { return this.visit_actionBase(e); } public visit_libAction(la: JLibAction): any { return this.visit_actionBase(la); } public visit_art(art: JArt): any { return this.visit_globalDef(art); } public visit_data(data: JData): any { return this.visit_globalDef(data); } public visit_library(lib: JLibrary): any { return this.visit_decl(lib); } public visit_typeBinding(type: JTypeBinding): any { return this.visit_binding(type); } public visit_actionBinding(action: JActionBinding): any { return this.visit_binding(action); } public visit_resolveClause(r: JResolveClause): any { return this.visit_node(r); } public visit_record(r: JRecord): any { return this.visit_decl(r); } public visit_recordField(rf: JRecordField): any { return this.visit_node(rf); } public visit_recordKey(rk: JRecordKey): any { return this.visit_recordField(rk); } public visit_app(app: JApp): any { return this.visit_node(app); } public visit_propertyParameter(p: JPropertyParameter): any { return null; } public visit_property(p: JProperty): any { return null; } public visit_typeDef(td: JTypeDef): any { return null; } public visit_apis(apis: JApis): any { return null; } /// abstract visitors public visit_node(node: JNode): any { return null; } public visit_token(tok: JToken):any { return this.visit_node(tok); } public visit_expr(tok: JExpr):any { return this.visit_token(tok); } public visit_stmt(n: JStmt):any { return this.visit_node(n); } public visit_stmts(sl: JStmt[]): any { return sl.map(this.visit_stmt); } public visit_actionBase(ab: JActionBase): any { return this.visit_decl(ab); } public visit_decl(d: JDecl): any { return this.visit_node(d); } public visit_condition(c: JCondition): any { return this.visit_node(c); } public visit_globalDef(g: JGlobalDef): any { return this.visit_decl(g); } public visit_binding(b: JBinding): any { return this.visit_node(b); } public dispatch(n: JNode):any { var propName = "visit_" + n.nodeType; var visitor = this[propName]; if (visitor) { return visitor.apply(this, [n]); } return null; } } export class VisitTokens extends NodeVisitor { public traverse_pre(node: JNode, visitor: NodeVisitor) { // visit this visitor.dispatch(node); this.children(node).forEach(v => this.traverse_pre(v, visitor)); } public children(node: JNode): JNode[]{ return this.dispatch(node); } /// visitor methods returning children in left to right order public visit_node(node:JNode): any { return []; } public visit_exprHolder(holder: TDev.AST.Json.JExprHolder): any { return holder.tokens; } public visit_exprStmt(node: JExprStmt): any { return [node.expr]; } public visit_inlineAction(action: JInlineAction): any { return action.body; } public visit_inlineActions(actions: JInlineActions): any { return actions.actions; } public visit_boxed(boxed: JBoxed): any { return boxed.body; } public visit_singletonRef(singleton: JSingletonRef): any { return []; } public visit_if(node: JIf): any { return [<any>node.condition].concat(node.thenBody).concat(node.elseBody); } public visit_propertyRef(property: JPropertyRef): any { return []; } public visit_localDef(local: JLocalDef): any { return []; } public visit_action(action: JAction): any { return action.body; } public visit_comment(comment: JComment): any { return []; } public visit_operator(op: JOperator): any { return []; } public visit_while(stmt: JWhile): any { return [<any>stmt.condition].concat(stmt.body); } public visit_for(stmt: JFor): any { return [<any>stmt.bound].concat(stmt.body); } public visit_foreach(stmt: JForeach): any { return [<any>stmt.collection].concat(stmt.conditions).concat(stmt.body); } public visit_where(clause: JWhere): any { return [clause.condition]; } public visit_typeRef(type: JTypeRef): any { return []; } public visit_placeholder(p: JPlaceholder): any { return []; } public visit_page(p: JPage): any { return p.initBody.concat(p.displayBody); } public visit_event(e: JEvent): any { return e.body; } public visit_libAction(la: JLibAction): any { return []; } public visit_art(art: JArt): any { return []; } public visit_data(data: JData): any { return []; } public visit_library(lib: JLibrary): any { return []; } public visit_typeBinding(type: JTypeBinding): any { return []; } public visit_actionBinding(action: JActionBinding): any { return []; } public visit_resolveClause(r: JResolveClause): any { return []; } public visit_record(r: JRecord): any { return []; } public visit_recordField(rf: JRecordField): any { return []; } public visit_recordKey(rk: JRecordKey): any { return []; } public visit_app(app: JApp): any { return app.decls; } public visit_propertyParameter(p: JPropertyParameter): any { return []; } public visit_property(p: JProperty): any { return []; } public visit_typeDef(td: JTypeDef): any { return []; } public visit_apis(apis: JApis): any { return []; } } export interface IResolver { resolve(prop: JPropertyRef): JProperty; resolveProp(parent:string, name:string): JProperty; returnType(prop: JProperty): string; } export class WebAPIResolver implements IResolver { private apiCache = {}; constructor(private apis: JApis) { apis.types.forEach((t) => { var tmap = {}; this.apiCache[t.name] = tmap; t.properties.forEach((p) => { tmap[p.name] = p; }); }); } public resolve(propref: JPropertyRef): JProperty { return this.resolveProp(<any>propref.parent, propref.name); } public resolveProp(parent: string, name: string): JProperty { var type = this.apiCache[parent]; if (type) { var prop = type[name]; return prop; } return null; } public returnType(prop: JProperty): string { return <any>prop.result.type; } } export interface IScriptResolver { dataType(id: JNodeRef): string; artType(id: JNodeRef): string; action(id: JNodeRef): JActionBase; asRecord(propref: JPropertyRef): JRecord; resolve(propref: JPropertyRef): JProperty; resolveProp(parent: string, name: string): JProperty; returnType(prop: JProperty): string; } export class ScriptResolver implements IScriptResolver { constructor(private apis: IResolver) { } private currentIds; public setCurrentScript(script: JApp) { this.currentIds = {}; script.decls.forEach(decl => { if (decl.nodeType == "data") { var d = <JData>decl; this.currentIds[d.id] = d.type; } else if (decl.nodeType == "art") { var art = <JArt>decl; this.currentIds[art.id] = art.type; } else if (decl.nodeType == "action") { this.addAction(<JAction>decl); } else if (decl.nodeType == "page") { var p = <JPage>decl; this.addAction(p); } else if (decl.nodeType == "library") { var lib = <JLibrary>decl; lib.exportedActions.forEach(a => this.addAction(a)); } else if (decl.nodeType == "record") { var rec = <JRecord>decl; this.currentIds[rec.name] = rec; } }); } private addAction(a: JActionBase) { this.currentIds[a.id] = a; } public dataType(id: JNodeRef): string { return this.currentIds[<any>id]; } public artType(id: JNodeRef): string { return this.currentIds[<any>id]; } public action(id: JNodeRef): JActionBase { return this.currentIds[<any>id]; } public asRecord(propref: JPropertyRef): JRecord { var rec = <JRecord>this.currentIds[<any>propref.parent]; if (rec && rec.nodeType == "record") { return rec; } return null; } public resolve(propref: JPropertyRef): JProperty { if (propref.declId) { var cand = this.currentIds[<any>propref.declId]; if (cand) { // TODO: } } return this.apis.resolve(propref); } public resolveProp(parent: string, name: string): JProperty { return this.apis.resolveProp(parent, name); } public returnType(prop: JProperty): string { return <any>prop.result.type; } public normalizeType(type: string): string { if (type && type.indexOf('{') >= 0) return "UserRecord"; var rec = <JRecord>this.currentIds[type]; if (rec && rec.nodeType == "record") { return "UserRecord"; } if (type.length > 6) { var end = type.slice(type.length - 6); if (end == " index") { return this.normalizeType(type.slice(0, type.length - 6)); } if (end == " table") { return this.normalizeType(type.slice(0, type.length - 6)); } if (type.length > 11) { end = type.slice(type.length - 10); if (end == " decorator") { return this.normalizeType(type.slice(0, type.length - 10)) + " decorator"; } } } return type; } } }
the_stack
import * as assert from "assert"; import { MIRResolvedTypeKey } from "../../compiler/mir_ops"; type VerifierOptions = { ISize: number, //bits used for Int/Nat StringOpt: "ASCII" | "UNICODE", EnableCollection_SmallHavoc: boolean, EnableCollection_LargeHavoc: boolean, EnableCollection_SmallOps: boolean, EnableCollection_LargeOps: boolean }; class BVEmitter { readonly bvsize: bigint; readonly natmax: bigint; readonly intmin: bigint; readonly intmax: bigint; readonly bvnatmax: SMTExp; readonly bvintmin: SMTExp; readonly bvintmax: SMTExp; readonly bvnatmax1: SMTExp; readonly bvintmin1: SMTExp; readonly bvintmax1: SMTExp; static computeBVMinSigned(bits: bigint): bigint { return -((2n ** bits) / 2n); } static computeBVMaxSigned(bits: bigint): bigint { return ((2n ** bits) / 2n) - 1n; } static computeBVMaxUnSigned(bits: bigint): bigint { return (2n ** bits) - 1n; } private static emitIntCore(val: bigint, imin: bigint, imax: bigint, bvsize: bigint): SMTExp { if(val === 0n) { return new SMTConst("BInt@zero"); } else { if (val > 0n) { assert(BigInt(val) <= imax); return new SMTConst(`(_ bv${val} ${bvsize})`); } else { assert(imin <= val); let bitstr = (-val).toString(2); let bits = ""; let carry = true; for(let i = bitstr.length - 1; i >= 0; --i) { const bs = (bitstr[i] === "0" ? "1" : "0"); if(bs === "0") { bits = (carry ? "1": "0") + bits; carry = false; } else { if(!carry) { bits = "1" + bits; //carry stays false } else { bits = "0" + bits; carry = true; } } } while(bits.length < bvsize) { bits = "1" + bits; } return new SMTConst(`#b${bits}`); } } } private static emitNatCore(val: bigint, nmax: bigint, bvsize: bigint): SMTExp { if(val === 0n) { return new SMTConst("BNat@zero"); } else { assert(0n < val && val <= nmax); return new SMTConst(`(_ bv${val} ${bvsize})`); } } constructor(bvsize: bigint, natmax: bigint, intmin: bigint, intmax: bigint, natmax1: bigint, intmin1: bigint, intmax1: bigint) { this.bvsize = bvsize; this.natmax = natmax; this.intmin = intmin; this.intmax = intmax; this.bvnatmax = BVEmitter.emitNatCore(natmax, natmax, bvsize); this.bvintmin = BVEmitter.emitIntCore(intmin, intmin, intmax, bvsize); this.bvintmax = BVEmitter.emitIntCore(intmax, intmin, intmax, bvsize); this.bvnatmax1 = BVEmitter.emitNatCore(natmax, natmax1, bvsize + 1n); this.bvintmin1 = BVEmitter.emitIntCore(intmin, intmin1, intmax1, bvsize + 1n); this.bvintmax1 = BVEmitter.emitIntCore(intmax, intmin1, intmax1, bvsize + 1n); } static create(bvsize: bigint): BVEmitter { return new BVEmitter(bvsize, BVEmitter.computeBVMaxUnSigned(bvsize), BVEmitter.computeBVMinSigned(bvsize), BVEmitter.computeBVMaxSigned(bvsize), BVEmitter.computeBVMaxUnSigned(bvsize + 1n), BVEmitter.computeBVMinSigned(bvsize + 1n), BVEmitter.computeBVMaxSigned(bvsize + 1n)); } emitIntGeneral(val: bigint): SMTExp { return BVEmitter.emitIntCore(val, this.intmin, this.intmax, this.bvsize); } emitNatGeneral(val: bigint): SMTExp { return BVEmitter.emitNatCore(val, this.natmax, this.bvsize); } emitSimpleInt(val: number): SMTExp { return this.emitIntGeneral(BigInt(val)); } emitSimpleNat(val: number): SMTExp { return this.emitNatGeneral(BigInt(val)); } emitInt(intv: string): SMTExp { return this.emitIntGeneral(BigInt(intv.slice(0, intv.length - 1))); } emitNat(natv: string): SMTExp { return this.emitNatGeneral(BigInt(natv.slice(0, natv.length - 1))); } } class SMTMaskConstruct { readonly maskname: string; readonly entries: SMTExp[] = []; constructor(maskname: string) { this.maskname = maskname; } emitSMT2(): string { return `($Mask_${this.entries.length}@cons ${this.entries.map((mv) => mv.emitSMT2(undefined)).join(" ")})`; } } class SMTType { readonly name: string; readonly smttypetag: string; readonly typeID: MIRResolvedTypeKey; constructor(name: string, smttypetag: string, typeid: MIRResolvedTypeKey) { this.name = name; this.smttypetag = smttypetag; this.typeID = typeid; } isGeneralKeyType(): boolean { return this.name === "BKey"; } isGeneralTermType(): boolean { return this.name === "BTerm"; } } abstract class SMTExp { abstract emitSMT2(indent: string | undefined): string; abstract computeCallees(callees: Set<string>): void; } class SMTVar extends SMTExp { readonly vname: string; constructor(vname: string) { super(); this.vname = vname; } emitSMT2(indent: string | undefined): string { return this.vname; } computeCallees(callees: Set<string>): void { //Nothing to do in many cases } } class SMTConst extends SMTExp { readonly cname: string; constructor(cname: string) { super(); this.cname = cname; } emitSMT2(indent: string | undefined): string { return this.cname; } computeCallees(callees: Set<string>): void { //Nothing to do in many cases } } class SMTCallSimple extends SMTExp { readonly fname: string; readonly args: SMTExp[]; constructor(fname: string, args: SMTExp[]) { super(); this.fname = fname; this.args = args; } emitSMT2(indent: string | undefined): string { return this.args.length === 0 ? this.fname : `(${this.fname} ${this.args.map((arg) => arg.emitSMT2(undefined)).join(" ")})`; } computeCallees(callees: Set<string>): void { callees.add(this.fname); this.args.forEach((arg) => arg.computeCallees(callees)); } static makeEq(lhs: SMTExp, rhs: SMTExp): SMTExp { return new SMTCallSimple("=", [lhs, rhs]); } static makeNotEq(lhs: SMTExp, rhs: SMTExp): SMTExp { return new SMTCallSimple("not", [new SMTCallSimple("=", [lhs, rhs])]); } static makeBinOp(op: string, lhs: SMTExp, rhs: SMTExp): SMTExp { return new SMTCallSimple(op, [lhs, rhs]); } static makeIsTypeOp(smtname: string, exp: SMTExp): SMTExp { return new SMTCallSimple(`(_ is ${smtname})`, [exp]); } static makeNot(exp: SMTExp): SMTExp { return new SMTCallSimple("not", [exp]); } static makeAndOf(...exps: SMTExp[]): SMTExp { return new SMTCallSimple("and", exps); } static makeOrOf(...exps: SMTExp[]): SMTExp { return new SMTCallSimple("or", exps); } } class SMTCallGeneral extends SMTExp { readonly fname: string; readonly args: SMTExp[]; constructor(fname: string, args: SMTExp[]) { super(); this.fname = fname; this.args = args; } emitSMT2(indent: string | undefined): string { return this.args.length === 0 ? this.fname : `(${this.fname} ${this.args.map((arg) => arg.emitSMT2(undefined)).join(" ")})`; } computeCallees(callees: Set<string>): void { callees.add(this.fname); this.args.forEach((arg) => arg.computeCallees(callees)); } } class SMTCallGeneralWOptMask extends SMTExp { readonly fname: string; readonly args: SMTExp[]; readonly mask: SMTMaskConstruct; constructor(fname: string, args: SMTExp[], mask: SMTMaskConstruct) { super(); this.fname = fname; this.args = args; this.mask = mask; } emitSMT2(indent: string | undefined): string { return this.args.length === 0 ? `(${this.fname} ${this.mask.emitSMT2()})` : `(${this.fname} ${this.args.map((arg) => arg.emitSMT2(undefined)).join(" ")} ${this.mask.emitSMT2()})`; } computeCallees(callees: Set<string>): void { callees.add(this.fname); this.args.forEach((arg) => arg.computeCallees(callees)); this.mask.entries.forEach((mentry) => mentry.computeCallees(callees)); } } class SMTCallGeneralWPassThroughMask extends SMTExp { readonly fname: string; readonly args: SMTExp[]; readonly mask: string; constructor(fname: string, args: SMTExp[], mask: string) { super(); this.fname = fname; this.args = args; this.mask = mask; } emitSMT2(indent: string | undefined): string { return this.args.length === 0 ? `(${this.fname} ${this.mask})` : `(${this.fname} ${this.args.map((arg) => arg.emitSMT2(undefined)).join(" ")} ${this.mask})`; } computeCallees(callees: Set<string>): void { callees.add(this.fname); this.args.forEach((arg) => arg.computeCallees(callees)); } } class SMTLet extends SMTExp { readonly vname: string; readonly value: SMTExp; readonly inexp: SMTExp; constructor(vname: string, value: SMTExp, inexp: SMTExp) { super(); this.vname = vname; this.value = value; this.inexp = inexp; } emitSMT2(indent: string | undefined): string { if (indent === undefined) { return `(let ((${this.vname} ${this.value.emitSMT2(undefined)})) ${this.inexp.emitSMT2(undefined)})`; } else { return `(let ((${this.vname} ${this.value.emitSMT2(undefined)}))\n${indent + " "}${this.inexp.emitSMT2(indent + " ")}\n${indent})`; } } computeCallees(callees: Set<string>): void { this.value.computeCallees(callees); this.inexp.computeCallees(callees); } } class SMTLetMulti extends SMTExp { readonly assigns: { vname: string, value: SMTExp }[]; readonly inexp: SMTExp constructor(assigns: { vname: string, value: SMTExp }[], inexp: SMTExp) { super(); this.assigns = assigns; this.inexp = inexp; } emitSMT2(indent: string | undefined): string { const binds = this.assigns.map((asgn) => `(${asgn.vname} ${asgn.value.emitSMT2(undefined)})`); if (indent === undefined) { return `(let (${binds.join(" ")}) ${this.inexp.emitSMT2(undefined)})`; } else { return `(let (${binds.join(" ")})\n${indent + " "}${this.inexp.emitSMT2(indent + " ")}\n${indent})`; } } computeCallees(callees: Set<string>): void { this.assigns.forEach((asgn) => { asgn.value.computeCallees(callees); }); this.inexp.computeCallees(callees); } } class SMTIf extends SMTExp { readonly cond: SMTExp; readonly tval: SMTExp; readonly fval: SMTExp; constructor(cond: SMTExp, tval: SMTExp, fval: SMTExp) { super(); this.cond = cond; this.tval = tval; this.fval = fval; } emitSMT2(indent: string | undefined): string { if (indent === undefined) { return `(ite ${this.cond.emitSMT2(undefined)} ${this.tval.emitSMT2(undefined)} ${this.fval.emitSMT2(undefined)})`; } else { return `(ite ${this.cond.emitSMT2(undefined)}\n${indent + " "}${this.tval.emitSMT2(indent + " ")}\n${indent + " "}${this.fval.emitSMT2(indent + " ")}\n${indent})`; } } computeCallees(callees: Set<string>): void { this.cond.computeCallees(callees); this.tval.computeCallees(callees); this.fval.computeCallees(callees); } } class SMTCond extends SMTExp { readonly opts: {test: SMTExp, result: SMTExp}[]; readonly orelse: SMTExp; constructor(opts: {test: SMTExp, result: SMTExp}[], orelse: SMTExp) { super(); this.opts = opts; this.orelse = orelse; } emitSMT2(indent: string | undefined): string { if (indent === undefined) { let iopts: string = this.orelse.emitSMT2(undefined); for(let i = this.opts.length - 1; i >= 0; --i) { iopts = `(ite ${this.opts[i].test.emitSMT2(undefined)} ${this.opts[i].result.emitSMT2(undefined)} ${iopts})` } return iopts; } else { let iopts: string = this.orelse.emitSMT2(undefined); for(let i = this.opts.length - 1; i >= 0; --i) { iopts = `(ite ${this.opts[i].test.emitSMT2(undefined)}\n${indent + " "}${this.opts[i].result.emitSMT2(indent + " ")}\n${indent + " "}${iopts}\n${indent})` } return iopts; } } computeCallees(callees: Set<string>): void { this.opts.forEach((opt) => { opt.test.computeCallees(callees); opt.result.computeCallees(callees); }); this.orelse.computeCallees(callees); } } class SMTADTKindSwitch extends SMTExp { readonly value: SMTExp; readonly opts: { cons: string, cargs: string[], result: SMTExp }[]; constructor(value: SMTExp, opts: { cons: string, cargs: string[], result: SMTExp }[]) { super(); this.value = value; this.opts = opts; } emitSMT2(indent: string | undefined): string { const matches = this.opts.map((op) => { const test = op.cargs.length !== 0 ? `(${op.cons} ${op.cargs.join(" ")})` : op.cons; return `(${test} ${op.result.emitSMT2(undefined)})`; }); if (indent === undefined) { return `(match ${this.value.emitSMT2(undefined)} (${matches.join(" ")}))`; } else { return `(match ${this.value.emitSMT2(undefined)} (\n${indent + " "}${matches.join("\n" + indent + " ")})\n${indent})`; } } computeCallees(callees: Set<string>): void { this.value.computeCallees(callees); this.opts.forEach((opt) => { opt.result.computeCallees(callees); }); } } class SMTForAll extends SMTExp { readonly terms: { vname: string, vtype: SMTType }[]; readonly clause: SMTExp; constructor(terms: { vname: string, vtype: SMTType }[], clause: SMTExp) { super(); this.terms = terms; this.clause = clause; } emitSMT2(indent: string | undefined): string { const terms = this.terms.map((t) => `(${t.vname} ${t.vtype.name})`); if(indent === undefined) { return `(forall (${terms.join(" ")}) ${this.clause.emitSMT2(undefined)})`; } else { return `(forall (${terms.join(" ")})\n${indent + " "}${this.clause.emitSMT2(indent + " ")}\n${indent})`; } } computeCallees(callees: Set<string>): void { this.clause.computeCallees(callees); } } class SMTExists extends SMTExp { readonly terms: { vname: string, vtype: SMTType }[]; readonly clause: SMTExp; constructor(terms: { vname: string, vtype: SMTType }[], clause: SMTExp) { super(); this.terms = terms; this.clause = clause; } emitSMT2(indent: string | undefined): string { const terms = this.terms.map((t) => `(${t.vname} ${t.vtype.name})`); if(indent === undefined) { return `(exists (${terms.join(" ")}) ${this.clause.emitSMT2(undefined)})`; } else { return `(exists (${terms.join(" ")})\n${indent + " "}${this.clause.emitSMT2(indent + " ")}\n${indent})`; } } computeCallees(callees: Set<string>): void { this.clause.computeCallees(callees); } } export { VerifierOptions, SMTMaskConstruct, BVEmitter, SMTType, SMTExp, SMTVar, SMTConst, SMTCallSimple, SMTCallGeneral, SMTCallGeneralWOptMask, SMTCallGeneralWPassThroughMask, SMTLet, SMTLetMulti, SMTIf, SMTCond, SMTADTKindSwitch, SMTForAll, SMTExists };
the_stack
import * as React from 'react'; import { Button, Dropdown, TextField, IconButton, Panel, PanelType, PrimaryButton, DefaultButton, CommandBar, MessageBar, MessageBarType, Spinner, SpinnerSize, DialogFooter, Pivot, PivotItem, CommandBarButton, IContextualMenuItem } from 'office-ui-fabric-react'; import styles from '../SiteDesignsStudio.module.scss'; import { escape, assign, find } from '@microsoft/sp-lodash-subset'; import { ISiteScriptContent, ISiteScriptAction, ISiteScript, SiteScriptEntitySchema } from '../../models/ISiteScript'; import Schema from '../../schema/schema'; import { IServiceConsumerComponentProps } from '../ISiteDesignsStudioProps'; import { ISiteScriptSchemaService, SiteScriptSchemaServiceKey } from '../../services/siteScriptSchema/SiteScriptSchemaService'; import ScriptActionAdder from '../scriptActionAdder/ScriptActionAdder'; import { SiteDesignsServiceKey, ISiteDesignsService } from '../../services/siteDesigns/SiteDesignsService'; import GenericObjectEditor from '../genericObjectEditor/GenericObjectEditor'; import { MonacoEditor } from '../monacoEditor/MonacoEditor'; import ScriptActionCollectionEditor from '../scriptActionEditor/ScriptActionCollectionEditor'; import { ISiteScriptActionUIWrapper } from '../../models/ISiteScriptActionUIWrapper'; import CreateListWizard from '../wizards/CreateListWizard'; const Ajv = require('ajv'); var ajv = new Ajv({ schemaId: 'auto' }); export enum EEditionMode { Design = 'design', Code = 'code', Split = 'split' } export interface ISiteScriptEditorState { script: ISiteScript; scriptContentJson: string; scriptActionUIs: ISiteScriptActionUIWrapper[]; schema: any; isValidContent: boolean; isInvalidSchema: boolean; isNewScript: boolean; editMode: EEditionMode; isLoading: boolean; hasError: boolean; userMessage: string; isEditingProperties: boolean; isAddingAction: boolean; addingActionVerb: string; allExpanded: boolean; allCollapsed: boolean; } export interface ISiteScriptEditorProps extends IServiceConsumerComponentProps { script: ISiteScript; onScriptUpdated?: (script: ISiteScript) => void; useWizardActionGenerators: boolean; useWizardPropertyEditors: boolean; } export default class SiteScriptEditor extends React.Component<ISiteScriptEditorProps, ISiteScriptEditorState> { private siteScriptSchemaService: ISiteScriptSchemaService; private siteDesignsService: ISiteDesignsService; private stateHistory: ISiteScriptEditorState[]; constructor(props: ISiteScriptEditorProps) { super(props); this.state = { script: null, scriptContentJson: '', scriptActionUIs: [], schema: null, isNewScript: false, isValidContent: true, isInvalidSchema: false, editMode: EEditionMode.Split, isLoading: true, hasError: false, userMessage: '', allExpanded: false, allCollapsed: true, isEditingProperties: false, isAddingAction: false, addingActionVerb: null }; } public componentWillMount() { this.props.serviceScope.whenFinished(() => { this.siteScriptSchemaService = this.props.serviceScope.consume(SiteScriptSchemaServiceKey); this.siteDesignsService = this.props.serviceScope.consume(SiteDesignsServiceKey); this._loadScript().then((loadedScript) => { const schema = this.siteScriptSchemaService.getSiteScriptSchema(); // If the script content is not loaded => ERROR if (!loadedScript.Content && loadedScript.Id) { this.setState({ script: null, scriptContentJson: 'INVALID SCHEMA', schema: schema, isLoading: false, isValidContent: false, hasError: true, userMessage: 'The specified script is invalid' }); return; } this.setState({ script: loadedScript, schema: schema, scriptActionUIs: this._buildScriptActionUIs(loadedScript, true, false), isNewScript: loadedScript.Id ? false : true, isLoading: false, isInvalidSchema: false, scriptContentJson: JSON.stringify(loadedScript.Content, null, 2) }); }); }); } public componentDidUpdate() { this._autoClearInfoMessages(); } private _loadScript(): Promise<ISiteScript> { let { script } = this.props; // If existing script (The Id is known) if (script.Id) { // Load that script return this.siteDesignsService.getSiteScript(script.Id); } else { // If the argument is a new script // Initialize the content return this._initializeScriptContent(script); } } private _getActionKey(index: number, parentActionKey?: string): string { return `${parentActionKey ? parentActionKey + '_' : ''}ACT_${index}`; } private _buildScriptActionUIs( script: ISiteScript, allCollapsed?: boolean, allExpanded?: boolean, singleExpandedActionKey?: string ): ISiteScriptActionUIWrapper[] { let { scriptActionUIs } = this.state; const checkIsExpanded = (actionKey: string, parentActionKey: string) => { if (singleExpandedActionKey) { // The action or its parent is expanded const shouldExpand = singleExpandedActionKey.indexOf(actionKey) == 0; return shouldExpand; } if (allExpanded == true) { return true; } if (allCollapsed == true) { return false; } let foundAction = null; if (scriptActionUIs && scriptActionUIs.length) { if (parentActionKey) { let parentAction = find(scriptActionUIs, (sau) => sau.key == parentActionKey); if (parentAction && parentAction.subactions) { foundAction = find(parentAction.subactions, (sau) => sau.key == actionKey); } } else { foundAction = find(scriptActionUIs, (sau) => sau.key == actionKey); } return foundAction && foundAction.isExpanded; } else { return false; } }; const mapper: ( action: ISiteScriptAction, index: number, parentActionKey?: string ) => ISiteScriptActionUIWrapper = (action, index, parentActionKey) => { let actionKey = this._getActionKey(index, parentActionKey); return { key: actionKey, action: action, isExpanded: checkIsExpanded(actionKey, parentActionKey), parentActionKey: parentActionKey, subactions: !action.subactions ? null : action.subactions.map((subaction, subactionIndex) => mapper(subaction, subactionIndex, actionKey)) }; }; return script.Content.actions.map((action, index) => mapper(action, index)); } public render(): React.ReactElement<ISiteScriptEditorProps> { let { isLoading, isEditingProperties, script, isNewScript, hasError, userMessage, isAddingAction } = this.state; if (isLoading) { return ( <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm6 ms-smOffset3"> <Spinner size={SpinnerSize.large} label="Loading..." /> </div> </div> ); } return ( <div> {userMessage && ( <MessageBar className={userMessage ? 'ms-fadeIn400' : 'ms-fadeOut400'} messageBarType={hasError ? MessageBarType.error : MessageBarType.success} > {userMessage} </MessageBar> )} {isAddingAction && ( <Panel isOpen={true} type={PanelType.medium}> {this._renderNewActionWizard()} </Panel> )} {(isNewScript || isEditingProperties) && this._renderSiteScriptPropertiesEditor()} <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <CommandBar items={this._getCommands()} farItems={this._getFarCommands()} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <div className={styles.designWorkspace}>{this._renderEditor()}</div> </div> </div> </div> ); } private editingSiteScriptProperties: ISiteScript = null; private _onSiteScriptPropertyChanged(propertyName: string, value: any) { if (!this.editingSiteScriptProperties) { this.editingSiteScriptProperties = { Id: '', Content: null, Description: '', Title: '', Version: 1 }; } if (propertyName == 'Version') { value = parseInt(value); } this.editingSiteScriptProperties[propertyName] = value; } private _renderSiteScriptPropertiesEditor() { if (!this.editingSiteScriptProperties) { let { script } = this.state; this.editingSiteScriptProperties = assign({}, script); } return ( <Panel isOpen={true} type={PanelType.smallFixedFar} onDismiss={() => this._cancelScriptPropertiesEdition()}> {this.editingSiteScriptProperties.Id && <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField value={this.editingSiteScriptProperties.Id} readOnly={true} label='Id' /> </div> </div>} <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField value={this.editingSiteScriptProperties.Title} label='Title' onChanged={v => this._onSiteScriptPropertyChanged('Title', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField multiline={true} rows={5} value={this.editingSiteScriptProperties.Description} label='Description' onChanged={v => this._onSiteScriptPropertyChanged('Description', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField value={this.editingSiteScriptProperties.Version.toString()} label='Version' onChanged={v => this._onSiteScriptPropertyChanged('Version', v)} /> </div> </div> <DialogFooter> <PrimaryButton text="Ok" onClick={() => this._applyPropertiesEdition()} /> <DefaultButton text="Cancel" onClick={() => this._cancelScriptPropertiesEdition()} /> </DialogFooter> </Panel> ); } private _renderEditor() { let { script, scriptActionUIs, schema, scriptContentJson, isInvalidSchema, isValidContent } = this.state; const codeEditor = ( <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <div className={styles.codeEditorContainer}> <MonacoEditor schema={schema} value={scriptContentJson} onValueChange={(content, errors) => this._onCodeUpdated(content, errors)} readOnly={false} /> </div> </div> </div> ); const designerEditor = isValidContent && ( <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <div className="ms-Grid-row"> <ScriptActionCollectionEditor serviceScope={this.props.serviceScope} actionUIs={scriptActionUIs} onActionRemoved={(actionKey) => this._removeScriptAction(actionKey)} onActionMoved={(actionKey, oldIndex, newIndex, parentActionKey) => this._moveAction(actionKey, parentActionKey, oldIndex, newIndex)} onActionChanged={(actionKey, action) => this._onActionUpdated(actionKey, action)} onExpandChanged={(actionUI) => this._onExpandChanged(actionUI)} getActionSchema={(action) => this.siteScriptSchemaService.getActionSchema(action)} useWizardPropertyEditors={this.props.useWizardPropertyEditors} /> </div> <div className="ms-Grid-row"> <div> <ScriptActionAdder serviceScope={this.props.serviceScope} onActionAdded={(a) => this._addScriptAction(a)} /> </div> </div> </div> </div> ); switch (this.state.editMode) { case EEditionMode.Code: return codeEditor; case EEditionMode.Design: return designerEditor; case EEditionMode.Split: default: return ( <div className={styles.splitWorkspace}> <div className={styles.splitPane}>{designerEditor}</div> <div className={styles.splitPane}>{codeEditor}</div> </div> ); } } private _renderNewActionWizard() { let { addingActionVerb } = this.state; let wizard = null; let wizardTitle = null; switch (addingActionVerb) { case 'createSPList': wizardTitle = 'Create a List'; wizard = ( <CreateListWizard serviceScope={this.props.serviceScope} actionVerb={addingActionVerb} createEmptyDescription={'Create an empty Create List action'} createEmptyLabel={'Empty'} createMagicDescription={'Create from an existing list in this site'} createMagicLabel={'From existing'} onScriptActionGenerated={(action) => this._onActionAdded(action)} onCancel={() => this._cancelWizard()} /> ); break; default: break; } return ( <Panel isOpen={true} hasCloseButton={false} type={PanelType.medium} headerText={wizardTitle}> {wizard} </Panel> ); } private _initializeScriptContent(script: ISiteScript): Promise<ISiteScript> { script.Content = this.siteScriptSchemaService.getNewSiteScript(); return Promise.resolve(script); } private _getCommands() { let { script, editMode, isValidContent, allExpanded, allCollapsed } = this.state; let actionsCount = script.Content.actions.length; const undoBtn: IContextualMenuItem = { key: 'undoBtn', text: 'Undo', title: 'Undo', disabled: !this._canUndo(), iconProps: { iconName: 'Undo' }, onClick: () => this._undo() }; const saveBtn: IContextualMenuItem = { key: 'saveBtn', text: 'Save', title: 'Save', iconProps: { iconName: 'Save' }, onClick: () => this._saveSiteScript() }; const editBtn: IContextualMenuItem = { key: 'btnEdit', text: 'Edit Properties', title: 'Edit Properties', iconProps: { iconName: 'Edit' }, onClick: () => this._editProperties() }; const expandAllBtn: IContextualMenuItem = { key: 'expandAllBtn', text: 'Expand All', title: 'Expand All', disabled: allExpanded, iconProps: { iconName: 'ExploreContent' }, onClick: () => this._setAllExpanded(true) }; const collapseAllBtn: IContextualMenuItem = { key: 'btnCollapseAll', text: 'Collapse All', title: 'Collapse All', disabled: allCollapsed, iconProps: { iconName: 'CollapseContent' }, onClick: () => this._setAllExpanded(false) }; let commands = [undoBtn]; if (isValidContent) { commands = commands.concat(saveBtn, editBtn); if (editMode != EEditionMode.Code) { commands = commands.concat(expandAllBtn, collapseAllBtn); } } return commands; } private _getFarCommands() { let { script, editMode, isValidContent } = this.state; let actionsCount = script.Content.actions.length; const designModeButton: IContextualMenuItem = { key: 'designModeBtn', text: 'Design', title: 'Design', iconProps: { iconName: 'Design' }, onClick: () => this._setEditionMode(EEditionMode.Design) }; const codeModeButton: IContextualMenuItem = { key: 'codeModeBtn', text: 'Code', title: 'Code', iconProps: { iconName: 'Code' }, onClick: () => this._setEditionMode(EEditionMode.Code) }; const splitModeButton: IContextualMenuItem = { key: 'splitModeBtn', text: 'Split', title: 'Split', iconProps: { iconName: 'Split' }, onClick: () => this._setEditionMode(EEditionMode.Split) }; return [designModeButton, codeModeButton, splitModeButton]; } private _setAllExpanded(isExpanded: boolean) { let { script } = this.state; let actions = script.Content.actions; this.setState({ allExpanded: isExpanded, allCollapsed: !isExpanded, scriptActionUIs: this._buildScriptActionUIs(script, !isExpanded, isExpanded) }); } private _setEditionMode(mode: EEditionMode) { this.setState({ editMode: mode }); } private _editProperties() { this.setState({ isEditingProperties: true }); } private _onExpandChanged(actionUI: ISiteScriptActionUIWrapper) { let { scriptActionUIs } = this.state; let allExpanded = true; let allCollapsed = false; const mapper: (mapActionUI: ISiteScriptActionUIWrapper) => ISiteScriptActionUIWrapper = (mapActionUI) => { allExpanded = allExpanded && mapActionUI.isExpanded; allCollapsed = !allCollapsed && !mapActionUI.isExpanded; if (mapActionUI.key == actionUI.key) { return actionUI; } else { let newActionUI = assign({}, mapActionUI); if (mapActionUI.subactions && mapActionUI.subactions.length) { newActionUI.subactions = mapActionUI.subactions.map(mapper); } return newActionUI; } }; let newActionUIs = scriptActionUIs.map(mapper); this.setState({ scriptActionUIs: newActionUIs, allExpanded: allExpanded, allCollapsed: allCollapsed }); } private _moveAction(actionKey: string, parentActionKey: string, oldIndex: number, newIndex: number) { let { script, scriptActionUIs } = this.state; let newActions: ISiteScriptActionUIWrapper[] = null; if (parentActionKey) { let parentActionUI = find(scriptActionUIs, (a) => a.key == parentActionKey); if (parentActionUI) { parentActionUI = assign({}, parentActionUI); let newSubActions = [].concat(parentActionUI.subactions) as ISiteScriptActionUIWrapper[]; let actionToMove = find(newSubActions, (a) => a.key == actionKey); newSubActions.splice(oldIndex, 1); newSubActions.splice(newIndex, 0, actionToMove); parentActionUI.subactions = newSubActions; newActions = scriptActionUIs.map((sau) => (sau.key == parentActionKey ? parentActionUI : sau)); } } else { newActions = [].concat(scriptActionUIs); let actionToMove = find(newActions, (a) => a.key == actionKey); newActions.splice(oldIndex, 1); newActions.splice(newIndex, 0, actionToMove); } const mapper: (mapActionUI: ISiteScriptActionUIWrapper) => ISiteScriptAction = (mapActionUI) => { let action = mapActionUI.action; if (mapActionUI.subactions && mapActionUI.subactions.length) { action.subactions = mapActionUI.subactions.map(mapper); } return action; }; let newContent = assign({}, script.Content); newContent.actions = newActions.map(mapper); let newScript = assign({}, script); newScript.Content = newContent; const newActionKey = this._getActionKey(newIndex, parentActionKey); this._saveToStateHistory(); this.setState({ script: newScript, scriptActionUIs: this._buildScriptActionUIs(newScript, null, null, newActionKey), scriptContentJson: JSON.stringify(newScript.Content, null, 2) }); } // Copy of the method in the GenericEditor // TODO Refactor this private _getPropertyDefaultValueFromSchema(schema: any, propertyName: string): any { let propSchema = schema.properties[propertyName]; if (propSchema) { switch (propSchema.type) { case 'string': return ''; case 'boolean': return false; case 'number': return 0; case 'object': return {}; default: return null; } } else { return null; } } private _getGenericScriptAction(verb: string): ISiteScriptAction { let newAction: ISiteScriptAction = { verb: verb }; let actionSchema = this.siteScriptSchemaService.getActionSchema(newAction); // Add default values for properties of the action if (actionSchema && actionSchema.properties) { Object.keys(actionSchema.properties) .filter((p) => p != 'verb') .forEach((p) => (newAction[p] = this._getPropertyDefaultValueFromSchema(actionSchema, p))); } console.log('Action Added: ', newAction); return newAction; } private _hasWizard(verb: string): boolean { const availableWizardsForAction = ['createSPList']; return availableWizardsForAction.indexOf(verb) > -1; } private _cancelWizard() { this.setState({ isAddingAction: false, addingActionVerb: null }); } private _addScriptAction(verb: string) { if (this._hasWizard(verb) && this.props.useWizardActionGenerators) { this.setState({ isAddingAction: true, addingActionVerb: verb }); } else { this._onActionAdded(this._getGenericScriptAction(verb)); } } private _onActionAdded(action: ISiteScriptAction) { let { script } = this.state; let newActionIndex = script.Content.actions.length; let newActionKey = this._getActionKey(newActionIndex); let newActionsArray = [].concat(script.Content.actions, action); let newScriptContent = assign({}, script.Content); newScriptContent.actions = newActionsArray; let newScript = assign({}, script); newScript.Content = newScriptContent; this._saveToStateHistory(); this.setState({ script: newScript, scriptActionUIs: this._buildScriptActionUIs(newScript, null, null, newActionKey), scriptContentJson: JSON.stringify(newScript.Content, null, 2), isAddingAction: false, addingActionVerb: null }); } private _removeScriptAction(actionKey: string) { let { script, scriptActionUIs } = this.state; let newActionsArray = scriptActionUIs.filter((item) => item.key != actionKey).map((a) => a.action); let newScriptContent = assign({}, script.Content); newScriptContent.actions = newActionsArray; let newScript = assign({}, script); newScript.Content = newScriptContent; this._saveToStateHistory(); this.setState({ script: newScript, scriptActionUIs: this._buildScriptActionUIs(newScript), scriptContentJson: JSON.stringify(newScript.Content, null, 2) }); } private _onActionUpdated(actionKey: string, action: ISiteScriptAction) { let { script, scriptActionUIs } = this.state; let newScript: ISiteScript = assign({}, script); let newScriptContent = assign({}, script.Content); // Check if the change is an added sub action // Get the action to update let previousAction = find(scriptActionUIs, (sau) => sau.key == actionKey); let previousSubActionsCount = previousAction.subactions && previousAction.subactions.length; let toExpandActionKey = null; if (previousSubActionsCount >= 0 && action.subactions && action.subactions.length > previousSubActionsCount) { // If a subaction is added, get the subaction key toExpandActionKey = this._getActionKey(previousSubActionsCount, actionKey); } newScriptContent.actions = [].concat(newScriptContent.actions); newScriptContent.actions = scriptActionUIs.map((sa) => (sa.key == actionKey ? action : sa.action)); newScript.Content = newScriptContent; this._saveToStateHistory(); this.setState({ script: newScript, scriptActionUIs: this._buildScriptActionUIs(newScript, null, null, toExpandActionKey), scriptContentJson: JSON.stringify(newScript.Content, null, 2) }); } private _onCodeUpdated(code: string, errors: any) { let { script, schema, scriptActionUIs } = this.state; let wereNoActions = scriptActionUIs.length == 0; // Validate the schema let parsedCode = JSON.parse(code); let valid = ajv.validate(schema, parsedCode); if (!valid) { console.error('Schema errors: ', ajv.errors); this.setState({ scriptContentJson: code, isLoading: false, isValidContent: false, hasError: true, userMessage: 'Oops... The Site Script is invalid...' }); } else { let newScript: ISiteScript = assign({}, script); let newScriptContent = parsedCode; newScript.Content = newScriptContent; this.setState({ script: newScript, scriptActionUIs: this._buildScriptActionUIs(newScript, false, wereNoActions), scriptContentJson: JSON.stringify(newScript.Content, null, 2), isValidContent: true, hasError: false, userMessage: null }); } } private _validateForSave(): string { let { schema, script } = this.state; if (!script.Title) { return 'The Site Script has no title'; } if (!script.Content) { return 'The Site Script has no content'; } // Check content schema validity let valid = ajv.validate(schema, script.Content); if (!valid) { return 'The Site Script is not valid against the Schena'; } return null; } private _saveSiteScript() { let { script } = this.state; let invalidMessage = this._validateForSave(); if (invalidMessage) { this.setState({ hasError: true, userMessage: invalidMessage }); return; } this.setState({ isLoading: true, isEditingProperties: false }); this.siteDesignsService .saveSiteScript(script) .then(() => { this.setState({ isEditingProperties: false, isNewScript: false, isLoading: false, hasError: false, userMessage: 'The site script have been properly saved' }); this._clearStateHistory(); }) .catch((error) => { this.setState({ isEditingProperties: false, hasError: true, isNewScript: false, isLoading: false, userMessage: 'The site script cannot be properly saved' }); }); } private _autoClearInfoMessages() { let { userMessage, hasError } = this.state; if (hasError) { return; } if (userMessage) { setTimeout(() => { this.setState({ userMessage: null }); }, 3000); } } private _applyPropertiesEdition() { if (!this.editingSiteScriptProperties) { return; } this.setState({ script: this.editingSiteScriptProperties, // scriptContentJson: JSON.stringify(siteScript.Content, null, 2), isEditingProperties: false, isNewScript: false }); if (this.props.onScriptUpdated) { this.props.onScriptUpdated(this.editingSiteScriptProperties); } this.editingSiteScriptProperties = null; } private _cancelScriptPropertiesEdition() { this.editingSiteScriptProperties = null; this.setState({ isEditingProperties: false, isNewScript: false }); } private _saveToStateHistory() { if (!this.stateHistory) { this.stateHistory = []; } if (this.stateHistory.length > 10) { this.stateHistory.splice(9, 1); } // Remove not relevant state properties let savedState = assign({}, this.state) as any; savedState.addingActionVerb = null; savedState.isAddingAction = false; savedState.isLoading = false; this.stateHistory.splice(0, 0, savedState); } private _clearStateHistory() { this.stateHistory = null; } private _undo() { if (!this.stateHistory || this.stateHistory.length == 0) { return; } let previousState = this.stateHistory[0]; this.stateHistory.splice(0, 1); this.setState(previousState); } private _canUndo(): boolean { return this.stateHistory && this.stateHistory.length > 0; } }
the_stack
import { EventEmitter } from 'events'; import { obx, makeObservable } from '@alilc/lowcode-editor-core'; import { NodeSchema } from '@alilc/lowcode-types'; import { setNativeSelection, cursor } from '@alilc/lowcode-utils'; import { DropLocation } from './location'; import { Node, DocumentModel } from '../document'; import { ISimulatorHost, isSimulatorHost, NodeInstance, ComponentInstance } from '../simulator'; import { Designer } from './designer'; export interface LocateEvent { readonly type: 'LocateEvent'; /** * 浏览器窗口坐标系 */ readonly globalX: number; readonly globalY: number; /** * 原始事件 */ readonly originalEvent: MouseEvent | DragEvent; /** * 拖拽对象 */ readonly dragObject: DragObject; /** * 激活的感应器 */ sensor?: ISensor; // ======= 以下是 激活的 sensor 将填充的值 ======== /** * 浏览器事件响应目标 */ target?: Element | null; /** * 当前激活文档画布坐标系 */ canvasX?: number; canvasY?: number; /** * 激活或目标文档 */ documentModel?: DocumentModel; /** * 事件订正标识,初始构造时,从发起端构造,缺少 canvasX,canvasY, 需要经过订正才有 */ fixed?: true; } /** * 拖拽敏感板 */ export interface ISensor { /** * 是否可响应,比如面板被隐藏,可设置该值 false */ readonly sensorAvailable: boolean; /** * 给事件打补丁 */ fixEvent(e: LocateEvent): LocateEvent; /** * 定位并激活 */ locate(e: LocateEvent): DropLocation | undefined | null; /** * 是否进入敏感板区域 */ isEnter(e: LocateEvent): boolean; /** * 取消激活 */ deactiveSensor(): void; /** * 获取节点实例 */ getNodeInstanceFromElement(e: Element | null): NodeInstance<ComponentInstance> | null; } export type DragObject = DragNodeObject | DragNodeDataObject | DragAnyObject; export enum DragObjectType { // eslint-disable-next-line no-shadow Node = 'node', NodeData = 'nodedata', } export interface DragNodeObject { type: DragObjectType.Node; nodes: Node[]; } export interface DragNodeDataObject { type: DragObjectType.NodeData; data: NodeSchema | NodeSchema[]; thumbnail?: string; description?: string; [extra: string]: any; } export interface DragAnyObject { type: string; [key: string]: any; } export function isDragNodeObject(obj: any): obj is DragNodeObject { return obj && obj.type === DragObjectType.Node; } export function isDragNodeDataObject(obj: any): obj is DragNodeDataObject { return obj && obj.type === DragObjectType.NodeData; } export function isDragAnyObject(obj: any): obj is DragAnyObject { return obj && obj.type !== DragObjectType.NodeData && obj.type !== DragObjectType.Node; } export function isLocateEvent(e: any): e is LocateEvent { return e && e.type === 'LocateEvent'; } const SHAKE_DISTANCE = 4; /** * mouse shake check */ export function isShaken(e1: MouseEvent | DragEvent, e2: MouseEvent | DragEvent): boolean { if ((e1 as any).shaken) { return true; } if (e1.target !== e2.target) { return true; } return ( Math.pow(e1.clientY - e2.clientY, 2) + Math.pow(e1.clientX - e2.clientX, 2) > SHAKE_DISTANCE ); } function isInvalidPoint(e: any, last: any): boolean { return ( e.clientX === 0 && e.clientY === 0 && last && (Math.abs(last.clientX - e.clientX) > 5 || Math.abs(last.clientY - e.clientY) > 5) ); } function isSameAs(e1: MouseEvent | DragEvent, e2: MouseEvent | DragEvent): boolean { return e1.clientY === e2.clientY && e1.clientX === e2.clientX; } export function setShaken(e: any) { e.shaken = true; } function getSourceSensor(dragObject: DragObject): ISimulatorHost | null { if (!isDragNodeObject(dragObject)) { return null; } return dragObject.nodes[0]?.document.simulator || null; } /** * make a handler that listen all sensors:document, avoid frame lost */ function makeEventsHandler( boostEvent: MouseEvent | DragEvent, sensors: ISimulatorHost[], ): (fn: (sdoc: Document) => void) => void { const topDoc = window.document; const sourceDoc = boostEvent.view?.document || topDoc; // TODO: optimize this logic, reduce listener const docs = new Set<Document>(); docs.add(topDoc); docs.add(sourceDoc); sensors.forEach((sim) => { const sdoc = sim.contentDocument; if (sdoc) { docs.add(sdoc); } }); return (handle: (sdoc: Document) => void) => { docs.forEach((doc) => handle(doc)); }; } function isDragEvent(e: any): e is DragEvent { return e?.type?.startsWith('drag'); } /** * Drag-on 拖拽引擎 */ export class Dragon { private sensors: ISensor[] = []; /** * current active sensor, 可用于感应区高亮 */ @obx.ref private _activeSensor: ISensor | undefined; get activeSensor(): ISensor | undefined { return this._activeSensor; } @obx.ref private _dragging = false; @obx.ref private _canDrop = false; get dragging(): boolean { return this._dragging; } private emitter = new EventEmitter(); constructor(readonly designer: Designer) { makeObservable(this); } /** * Quick listen a shell(container element) drag behavior * @param shell container element * @param boost boost got a drag object */ from(shell: Element, boost: (e: MouseEvent) => DragObject | null) { const mousedown = (e: MouseEvent) => { // ESC or RightClick if (e.which === 3 || e.button === 2) { return; } // Get a new node to be dragged const dragObject = boost(e); if (!dragObject) { return; } this.boost(dragObject, e); }; shell.addEventListener('mousedown', mousedown as any); return () => { shell.removeEventListener('mousedown', mousedown as any); }; } /** * boost your dragObject for dragging(flying) 发射拖拽对象 * * @param dragObject 拖拽对象 * @param boostEvent 拖拽初始时事件 */ boost(dragObject: DragObject, boostEvent: MouseEvent | DragEvent, fromRglNode?: Node) { const { designer } = this; const masterSensors = this.getMasterSensors(); const handleEvents = makeEventsHandler(boostEvent, masterSensors); const newBie = !isDragNodeObject(dragObject); const forceCopyState = isDragNodeObject(dragObject) && dragObject.nodes.some((node) => node.isSlot()); const isBoostFromDragAPI = isDragEvent(boostEvent); let lastSensor: ISensor | undefined; this._dragging = false; const getRGL = (e: MouseEvent | DragEvent) => { const locateEvent = createLocateEvent(e); const sensor = chooseSensor(locateEvent); if (!sensor || !sensor.getNodeInstanceFromElement) return {}; const nodeInst = sensor.getNodeInstanceFromElement(e.target as Element); return nodeInst?.node?.getRGL() || {}; }; const checkesc = (e: KeyboardEvent) => { if (e.keyCode === 27) { designer.clearLocation(); over(); } }; let copy = false; const checkcopy = (e: MouseEvent | DragEvent | KeyboardEvent) => { /* istanbul ignore next */ if (isDragEvent(e) && e.dataTransfer) { if (newBie || forceCopyState) { e.dataTransfer.dropEffect = 'copy'; } return; } if (newBie) { return; } if (e.altKey || e.ctrlKey) { copy = true; this.setCopyState(true); /* istanbul ignore next */ if (isDragEvent(e) && e.dataTransfer) { e.dataTransfer.dropEffect = 'copy'; } } else { copy = false; if (!forceCopyState) { this.setCopyState(false); /* istanbul ignore next */ if (isDragEvent(e) && e.dataTransfer) { e.dataTransfer.dropEffect = 'move'; } } } }; let lastArrive: any; const drag = (e: MouseEvent | DragEvent) => { // FIXME: donot setcopy when: newbie & no location checkcopy(e); if (isInvalidPoint(e, lastArrive)) return; if (lastArrive && isSameAs(e, lastArrive)) { lastArrive = e; return; } lastArrive = e; const { isRGL, rglNode } = getRGL(e); const locateEvent = createLocateEvent(e); const sensor = chooseSensor(locateEvent); if (isRGL) { // 禁止被拖拽元素的阻断 const nodeInst = dragObject.nodes[0].getDOMNode(); if (nodeInst && nodeInst.style) { this.nodeInstPointerEvents = true; nodeInst.style.pointerEvents = 'none'; } // 原生拖拽 this.emitter.emit('rgl.sleeping', false); if (fromRglNode && fromRglNode.id === rglNode.id) { designer.clearLocation(); this.clearState(); this.emitter.emit('drag', locateEvent); return; } this._canDrop = !!sensor?.locate(locateEvent); if (this._canDrop) { this.emitter.emit('rgl.add.placeholder', { rglNode, fromRglNode, node: locateEvent.dragObject.nodes[0], event: e, }); designer.clearLocation(); this.clearState(); this.emitter.emit('drag', locateEvent); return; } } else { this._canDrop = false; this.emitter.emit('rgl.remove.placeholder'); this.emitter.emit('rgl.sleeping', true); } if (sensor) { sensor.fixEvent(locateEvent); sensor.locate(locateEvent); } else { designer.clearLocation(); } this.emitter.emit('drag', locateEvent); }; const dragstart = () => { this._dragging = true; setShaken(boostEvent); const locateEvent = createLocateEvent(boostEvent); if (newBie || forceCopyState) { this.setCopyState(true); } else { chooseSensor(locateEvent); } this.setDraggingState(true); // ESC cancel drag if (!isBoostFromDragAPI) { handleEvents((doc) => { doc.addEventListener('keydown', checkesc, false); }); } this.emitter.emit('dragstart', locateEvent); }; // route: drag-move const move = (e: MouseEvent | DragEvent) => { /* istanbul ignore next */ if (isBoostFromDragAPI) { e.preventDefault(); } if (this._dragging) { // process dragging drag(e); return; } // first move check is shaken if (isShaken(boostEvent, e)) { // is shaken dragstart dragstart(); drag(e); } }; let didDrop = true; /* istanbul ignore next */ const drop = (e: DragEvent) => { e.preventDefault(); e.stopPropagation(); didDrop = true; }; // end-tail drag process const over = (e?: any) => { // 禁止被拖拽元素的阻断 if (this.nodeInstPointerEvents) { const nodeInst = dragObject.nodes[0].getDOMNode(); if (nodeInst && nodeInst.style) { nodeInst.style.pointerEvents = ''; } this.nodeInstPointerEvents = false; } // 发送drop事件 if (e) { const { isRGL, rglNode } = getRGL(e); if (isRGL && this._canDrop) { const tarNode = dragObject.nodes[0]; if (rglNode.id !== tarNode.id) { // 避免死循环 this.emitter.emit('rgl.drop', { rglNode, node: tarNode, }); const { selection } = designer.project.currentDocument; selection.select(tarNode.id); } } } // 移除磁帖占位消息 this.emitter.emit('rgl.remove.placeholder'); /* istanbul ignore next */ if (e && isDragEvent(e)) { e.preventDefault(); } if (lastSensor) { lastSensor.deactiveSensor(); } /* istanbul ignore next */ if (isBoostFromDragAPI) { if (!didDrop) { designer.clearLocation(); } } else { this.setNativeSelection(true); } this.clearState(); let exception; if (this._dragging) { this._dragging = false; try { this.emitter.emit('dragend', { dragObject, copy }); } catch (ex) { exception = ex; } } designer.clearLocation(); handleEvents((doc) => { /* istanbul ignore next */ if (isBoostFromDragAPI) { doc.removeEventListener('dragover', move, true); doc.removeEventListener('dragend', over, true); doc.removeEventListener('drop', drop, true); } else { doc.removeEventListener('mousemove', move, true); doc.removeEventListener('mouseup', over, true); } doc.removeEventListener('mousedown', over, true); doc.removeEventListener('keydown', checkesc, false); doc.removeEventListener('keydown', checkcopy, false); doc.removeEventListener('keyup', checkcopy, false); }); if (exception) { throw exception; } }; // create drag locate event const createLocateEvent = (e: MouseEvent | DragEvent): LocateEvent => { const evt: any = { type: 'LocateEvent', dragObject, target: e.target, originalEvent: e, }; const sourceDocument = e.view?.document; // event from current document if (!sourceDocument || sourceDocument === document) { evt.globalX = e.clientX; evt.globalY = e.clientY; } /* istanbul ignore next */ else { // event from simulator sandbox let srcSim: ISimulatorHost | undefined; const lastSim = lastSensor && isSimulatorHost(lastSensor) ? lastSensor : null; // check source simulator if (lastSim && lastSim.contentDocument === sourceDocument) { srcSim = lastSim; } else { srcSim = masterSensors.find((sim) => sim.contentDocument === sourceDocument); if (!srcSim && lastSim) { srcSim = lastSim; } } if (srcSim) { // transform point by simulator const g = srcSim.viewport.toGlobalPoint(e); evt.globalX = g.clientX; evt.globalY = g.clientY; evt.canvasX = e.clientX; evt.canvasY = e.clientY; evt.sensor = srcSim; } else { // this condition will not happen, just make sure ts ok evt.globalX = e.clientX; evt.globalY = e.clientY; } } return evt; }; const sourceSensor = getSourceSensor(dragObject); /* istanbul ignore next */ const chooseSensor = (e: LocateEvent) => { // this.sensors will change on dragstart const sensors: ISensor[] = this.sensors.concat(masterSensors as ISensor[]); let sensor = e.sensor && e.sensor.isEnter(e) ? e.sensor : sensors.find((s) => s.sensorAvailable && s.isEnter(e)); if (!sensor) { // TODO: enter some area like componentspanel cancel if (lastSensor) { sensor = lastSensor; } else if (e.sensor) { sensor = e.sensor; } else if (sourceSensor) { sensor = sourceSensor; } } if (sensor !== lastSensor) { if (lastSensor) { lastSensor.deactiveSensor(); } lastSensor = sensor; } if (sensor) { e.sensor = sensor; sensor.fixEvent(e); } this._activeSensor = sensor; return sensor; }; /* istanbul ignore next */ if (isDragEvent(boostEvent)) { const { dataTransfer } = boostEvent; if (dataTransfer) { dataTransfer.effectAllowed = 'all'; try { dataTransfer.setData('application/json', '{}'); } catch (ex) { // ignore } } dragstart(); } else { this.setNativeSelection(false); } handleEvents((doc) => { /* istanbul ignore next */ if (isBoostFromDragAPI) { doc.addEventListener('dragover', move, true); // dragexit didDrop = false; doc.addEventListener('drop', drop, true); doc.addEventListener('dragend', over, true); } else { doc.addEventListener('mousemove', move, true); doc.addEventListener('mouseup', over, true); } doc.addEventListener('mousedown', over, true); }); // future think: drag things from browser-out or a iframe-pane if (!newBie && !isBoostFromDragAPI) { handleEvents((doc) => { doc.addEventListener('keydown', checkcopy, false); doc.addEventListener('keyup', checkcopy, false); }); } } private getMasterSensors(): ISimulatorHost[] { return Array.from( new Set( this.designer.project.documents .map((doc) => { if (doc.active && doc.simulator?.sensorAvailable) { return doc.simulator; } return null; }) .filter(Boolean) as any, ), ); } private getSimulators() { return new Set(this.designer.project.documents.map((doc) => doc.simulator)); } // #region ======== drag and drop helpers ============ private setNativeSelection(enableFlag: boolean) { setNativeSelection(enableFlag); this.getSimulators().forEach((sim) => { sim?.setNativeSelection(enableFlag); }); } /** * 设置拖拽态 */ private setDraggingState(state: boolean) { cursor.setDragging(state); this.getSimulators().forEach((sim) => { sim?.setDraggingState(state); }); } /** * 设置拷贝态 */ private setCopyState(state: boolean) { cursor.setCopy(state); this.getSimulators().forEach((sim) => { sim?.setCopyState(state); }); } /** * 清除所有态:拖拽态、拷贝态 */ private clearState() { cursor.release(); this.getSimulators().forEach((sim) => { sim?.clearState(); }); } // #endregion /** * 添加投放感应区 */ addSensor(sensor: any) { this.sensors.push(sensor); } /** * 移除投放感应 */ removeSensor(sensor: any) { const i = this.sensors.indexOf(sensor); if (i > -1) { this.sensors.splice(i, 1); } } onDragstart(func: (e: LocateEvent) => any) { this.emitter.on('dragstart', func); return () => { this.emitter.removeListener('dragstart', func); }; } onDrag(func: (e: LocateEvent) => any) { this.emitter.on('drag', func); return () => { this.emitter.removeListener('drag', func); }; } onDragend(func: (x: { dragObject: DragObject; copy: boolean }) => any) { this.emitter.on('dragend', func); return () => { this.emitter.removeListener('dragend', func); }; } }
the_stack
module android.widget { import Canvas = android.graphics.Canvas; import Rect = android.graphics.Rect; import Bundle = android.os.Bundle; import Log = android.util.Log; import FocusFinder = android.view.FocusFinder; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import VelocityTracker = android.view.VelocityTracker; import View = android.view.View; import ViewConfiguration = android.view.ViewConfiguration; import ViewGroup = android.view.ViewGroup; import ViewParent = android.view.ViewParent; import AnimationUtils = android.view.animation.AnimationUtils; import List = java.util.List; import Integer = java.lang.Integer; import System = java.lang.System; import FrameLayout = android.widget.FrameLayout; import LinearLayout = android.widget.LinearLayout; import ListView = android.widget.ListView; import OverScroller = android.widget.OverScroller; import Scroller = android.widget.Scroller; import TextView = android.widget.TextView; import AttrBinder = androidui.attr.AttrBinder; /** * Layout container for a view hierarchy that can be scrolled by the user, * allowing it to be larger than the physical display. A ScrollView * is a {@link FrameLayout}, meaning you should place one child in it * containing the entire contents to scroll; this child may itself be a layout * manager with a complex hierarchy of objects. A child that is often used * is a {@link LinearLayout} in a vertical orientation, presenting a vertical * array of top-level items that the user can scroll through. * <p>You should never use a ScrollView with a {@link ListView}, because * ListView takes care of its own vertical scrolling. Most importantly, doing this * defeats all of the important optimizations in ListView for dealing with * large lists, since it effectively forces the ListView to display its entire * list of items to fill up the infinite container supplied by ScrollView. * <p>The {@link TextView} class also * takes care of its own scrolling, so does not require a ScrollView, but * using the two together is possible to achieve the effect of a text view * within a larger container. * * <p>ScrollView only supports vertical scrolling. For horizontal scrolling, * use {@link HorizontalScrollView}. * * @attr ref android.R.styleable#ScrollView_fillViewport */ export class ScrollView extends FrameLayout { static ANIMATED_SCROLL_GAP: number = 250; static MAX_SCROLL_FACTOR: number = 0.5; private static TAG: string = "ScrollView"; private mLastScroll: number = 0; private mTempRect: Rect = new Rect(); private mScroller: OverScroller; // private mEdgeGlowTop:EdgeEffect; // // private mEdgeGlowBottom:EdgeEffect; /** * Position of the last motion event. */ private mLastMotionY: number = 0; /** * True when the layout has changed but the traversal has not come through yet. * Ideally the view hierarchy would keep track of this for us. */ private mIsLayoutDirty: boolean = true; /** * The child to give focus to in the event that a child has requested focus while the * layout is dirty. This prevents the scroll from being wrong if the child has not been * laid out before requesting focus. */ private mChildToScrollTo: View = null; /** * True if the user is currently dragging this ScrollView around. This is * not the same as 'is being flinged', which can be checked by * mScroller.isFinished() (flinging begins when the user lifts his finger). */ private mIsBeingDragged: boolean = false; /** * Determines speed during touch scrolling */ private mVelocityTracker: VelocityTracker; /** * When set to true, the scroll view measure its child to make it fill the currently * visible area. */ private mFillViewport: boolean; /** * Whether arrow scrolling is animated. */ private mSmoothScrollingEnabled: boolean = true; // private mTouchSlop:number = 0; private mMinimumVelocity: number = 0; private mMaximumVelocity: number = 0; private mOverscrollDistance: number = 0; private mOverflingDistance: number = 0; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private mActivePointerId: number = ScrollView.INVALID_POINTER; // /** // * The StrictMode "critical time span" objects to catch animation // * stutters. Non-null when a time-sensitive animation is // * in-flight. Must call finish() on them when done animating. // * These are no-ops on user builds. // */ // // aka "drag" // private mScrollStrictSpan:StrictMode.Span = null; // // private mFlingStrictSpan:StrictMode.Span = null; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static INVALID_POINTER: number = -1; // private mSavedState:ScrollView.SavedState; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=R.attr.scrollViewStyle) { super(context, bindElement, defStyle); this.initScrollView(); const a = context.obtainStyledAttributes(bindElement, defStyle); this.setFillViewport(a.getBoolean('fillViewport', false)); a.recycle(); } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('fillViewport', { setter(v:ScrollView, value:any, attrBinder:AttrBinder) { v.setFillViewport(attrBinder.parseBoolean(value)); }, getter(v:ScrollView) { return v.isFillViewport(); } }); } shouldDelayChildPressedState(): boolean { return true; } protected getTopFadingEdgeStrength(): number { if (this.getChildCount() == 0) { return 0.0; } const length: number = this.getVerticalFadingEdgeLength(); if (this.mScrollY < length) { return this.mScrollY / <number> length; } return 1.0; } protected getBottomFadingEdgeStrength(): number { if (this.getChildCount() == 0) { return 0.0; } const length: number = this.getVerticalFadingEdgeLength(); const bottomEdge: number = this.getHeight() - this.mPaddingBottom; const span: number = this.getChildAt(0).getBottom() - this.mScrollY - bottomEdge; if (span < length) { return span / <number> length; } return 1.0; } /** * @return The maximum amount this scroll view will scroll in response to * an arrow event. */ getMaxScrollAmount(): number { return Math.floor((ScrollView.MAX_SCROLL_FACTOR * (this.mBottom - this.mTop))); } private initScrollView(): void { this.mScroller = new OverScroller(); this.setFocusable(true); this.setDescendantFocusability(ScrollView.FOCUS_AFTER_DESCENDANTS); this.setWillNotDraw(false); const configuration: ViewConfiguration = ViewConfiguration.get(this.mContext); this.mTouchSlop = configuration.getScaledTouchSlop(); this.mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); this.mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); this.mOverscrollDistance = configuration.getScaledOverscrollDistance(); this.mOverflingDistance = configuration.getScaledOverflingDistance(); } addView(...args): void { if (this.getChildCount() > 0) { throw new Error("ScrollView can host only one direct child"); } return super.addView(...args); } /** * @return Returns true this ScrollView can be scrolled */ private canScroll(): boolean { let child: View = this.getChildAt(0); if (child != null) { let childHeight: number = child.getHeight(); return this.getHeight() < childHeight + this.mPaddingTop + this.mPaddingBottom; } return false; } /** * Indicates whether this ScrollView's content is stretched to fill the viewport. * * @return True if the content fills the viewport, false otherwise. * * @attr ref android.R.styleable#ScrollView_fillViewport */ isFillViewport(): boolean { return this.mFillViewport; } /** * Indicates this ScrollView whether it should stretch its content height to fill * the viewport or not. * * @param fillViewport True to stretch the content's height to the viewport's * boundaries, false otherwise. * * @attr ref android.R.styleable#ScrollView_fillViewport */ setFillViewport(fillViewport: boolean): void { if (fillViewport != this.mFillViewport) { this.mFillViewport = fillViewport; this.requestLayout(); } } /** * @return Whether arrow scrolling will animate its transition. */ isSmoothScrollingEnabled(): boolean { return this.mSmoothScrollingEnabled; } /** * Set whether arrow scrolling will animate its transition. * @param smoothScrollingEnabled whether arrow scrolling will animate its transition */ setSmoothScrollingEnabled(smoothScrollingEnabled: boolean): void { this.mSmoothScrollingEnabled = smoothScrollingEnabled; } protected onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (!this.mFillViewport) { return; } const heightMode: number = View.MeasureSpec.getMode(heightMeasureSpec); if (heightMode == View.MeasureSpec.UNSPECIFIED) { return; } if (this.getChildCount() > 0) { const child: View = this.getChildAt(0); let height: number = this.getMeasuredHeight(); if (child.getMeasuredHeight() < height) { const lp: FrameLayout.LayoutParams = <FrameLayout.LayoutParams> child.getLayoutParams(); let childWidthMeasureSpec: number = ScrollView.getChildMeasureSpec(widthMeasureSpec, this.mPaddingLeft + this.mPaddingRight, lp.width); height -= this.mPaddingTop; height -= this.mPaddingBottom; let childHeightMeasureSpec: number = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } } dispatchKeyEvent(event: KeyEvent): boolean { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || this.executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ executeKeyEvent(event: KeyEvent): boolean { this.mTempRect.setEmpty(); if (!this.canScroll()) { if (this.isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) { let currentFocused: View = this.findFocus(); if (currentFocused == this) currentFocused = null; let nextFocused: View = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN); return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN); } return false; } let handled: boolean = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: if (!event.isAltPressed()) { handled = this.arrowScroll(View.FOCUS_UP); } else { handled = this.fullScroll(View.FOCUS_UP); } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (!event.isAltPressed()) { handled = this.arrowScroll(View.FOCUS_DOWN); } else { handled = this.fullScroll(View.FOCUS_DOWN); } break; case KeyEvent.KEYCODE_SPACE: this.pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN); break; } } return handled; } private inChild(x: number, y: number): boolean { if (this.getChildCount() > 0) { const scrollY: number = this.mScrollY; const child: View = this.getChildAt(0); return !(y < child.getTop() - scrollY || y >= child.getBottom() - scrollY || x < child.getLeft() || x >= child.getRight()); } return false; } private initOrResetVelocityTracker(): void { if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } else { this.mVelocityTracker.clear(); } } private initVelocityTrackerIfNotExists(): void { if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } } private recycleVelocityTracker(): void { if (this.mVelocityTracker != null) { this.mVelocityTracker.recycle(); this.mVelocityTracker = null; } } requestDisallowInterceptTouchEvent(disallowIntercept: boolean): void { if (disallowIntercept) { this.recycleVelocityTracker(); } super.requestDisallowInterceptTouchEvent(disallowIntercept); } onInterceptTouchEvent(ev: MotionEvent): boolean { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ const action: number = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (this.mIsBeingDragged)) { return true; } /* * Don't try to intercept touch if we can't scroll anyway. */ if (this.getScrollY() == 0 && !this.canScrollVertically(1)) { return false; } switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ const activePointerId: number = this.mActivePointerId; if (activePointerId == ScrollView.INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } const pointerIndex: number = ev.findPointerIndex(activePointerId); if (pointerIndex == -1) { Log.e(ScrollView.TAG, "Invalid pointerId=" + activePointerId + " in onInterceptTouchEvent"); break; } const y: number = Math.floor(ev.getY(pointerIndex)); const yDiff: number = Math.abs(y - this.mLastMotionY); if (yDiff > this.mTouchSlop) { this.mIsBeingDragged = true; this.mLastMotionY = y; this.initVelocityTrackerIfNotExists(); this.mVelocityTracker.addMovement(ev); // if (this.mScrollStrictSpan == null) { // this.mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); // } const parent: ViewParent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } break; } case MotionEvent.ACTION_DOWN: { const y: number = Math.floor(ev.getY()); if (!this.inChild(Math.floor(ev.getX()), Math.floor(y))) { this.mIsBeingDragged = false; this.recycleVelocityTracker(); break; } /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ this.mLastMotionY = y; this.mActivePointerId = ev.getPointerId(0); this.initOrResetVelocityTracker(); this.mVelocityTracker.addMovement(ev); /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ this.mIsBeingDragged = !this.mScroller.isFinished(); // if (this.mIsBeingDragged && this.mScrollStrictSpan == null) { // this.mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll"); // } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: /* Release the drag */ this.mIsBeingDragged = false; this.mActivePointerId = ScrollView.INVALID_POINTER; this.recycleVelocityTracker(); if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, 0, 0, this.getScrollRange())) { this.postInvalidateOnAnimation(); } break; case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return this.mIsBeingDragged; } onTouchEvent(ev: MotionEvent): boolean { this.initVelocityTrackerIfNotExists(); this.mVelocityTracker.addMovement(ev); const action: number = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { if (this.getChildCount() == 0) { return false; } if ((this.mIsBeingDragged = !this.mScroller.isFinished())) { const parent: ViewParent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ if (!this.mScroller.isFinished()) { this.mScroller.abortAnimation(); // if (this.mFlingStrictSpan != null) { // this.mFlingStrictSpan.finish(); // this.mFlingStrictSpan = null; // } } // Remember where the motion event started this.mLastMotionY = Math.floor(ev.getY()); this.mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: const activePointerIndex: number = ev.findPointerIndex(this.mActivePointerId); if (activePointerIndex == -1) { Log.e(ScrollView.TAG, "Invalid pointerId=" + this.mActivePointerId + " in onTouchEvent"); break; } const y: number = Math.floor(ev.getY(activePointerIndex)); let deltaY: number = this.mLastMotionY - y; if (!this.mIsBeingDragged && Math.abs(deltaY) > this.mTouchSlop) { const parent: ViewParent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } this.mIsBeingDragged = true; if (deltaY > 0) { deltaY -= this.mTouchSlop; } else { deltaY += this.mTouchSlop; } } if (this.mIsBeingDragged) { // Scroll to follow the motion event this.mLastMotionY = y; const oldX: number = this.mScrollX; const oldY: number = this.mScrollY; const range: number = this.getScrollRange(); const overscrollMode: number = this.getOverScrollMode(); const canOverscroll: boolean = overscrollMode == ScrollView.OVER_SCROLL_ALWAYS || (overscrollMode == ScrollView.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); // calls onScrollChanged if applicable. if (this.overScrollBy(0, deltaY, 0, this.mScrollY, 0, range, 0, this.mOverscrollDistance, true)) { // Break our velocity if we hit a scroll barrier. this.mVelocityTracker.clear(); } // if (canOverscroll) { // const pulledToY:number = oldY + deltaY; // if (pulledToY < 0) { // this.mEdgeGlowTop.onPull(<number> deltaY / this.getHeight()); // if (!this.mEdgeGlowBottom.isFinished()) { // this.mEdgeGlowBottom.onRelease(); // } // } else if (pulledToY > range) { // this.mEdgeGlowBottom.onPull(<number> deltaY / this.getHeight()); // if (!this.mEdgeGlowTop.isFinished()) { // this.mEdgeGlowTop.onRelease(); // } // } // if (this.mEdgeGlowTop != null && (!this.mEdgeGlowTop.isFinished() || !this.mEdgeGlowBottom.isFinished())) { // this.postInvalidateOnAnimation(); // } // } } break; case MotionEvent.ACTION_UP: if (this.mIsBeingDragged) { const velocityTracker: VelocityTracker = this.mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity); let initialVelocity: number = Math.floor(velocityTracker.getYVelocity(this.mActivePointerId)); if (this.getChildCount() > 0) { const springBack = this.mScrollY < -this.mOverflingDistance || this.mScrollY - this.getScrollRange() > this.mOverflingDistance; if (!springBack && (Math.abs(initialVelocity) > this.mMinimumVelocity)) { this.fling(-initialVelocity); } else { if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, 0, 0, this.getScrollRange())) { this.postInvalidateOnAnimation(); } } } this.mActivePointerId = ScrollView.INVALID_POINTER; this.endDrag(); } break; case MotionEvent.ACTION_CANCEL: if (this.mIsBeingDragged && this.getChildCount() > 0) { if (this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, 0, 0, this.getScrollRange())) { this.postInvalidateOnAnimation(); } this.mActivePointerId = ScrollView.INVALID_POINTER; this.endDrag(); } break; case MotionEvent.ACTION_POINTER_DOWN: { const index: number = ev.getActionIndex(); this.mLastMotionY = Math.floor(ev.getY(index)); this.mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); this.mLastMotionY = Math.floor(ev.getY(ev.findPointerIndex(this.mActivePointerId))); break; } return true; } private onSecondaryPointerUp(ev: MotionEvent): void { const pointerIndex: number = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; const pointerId: number = ev.getPointerId(pointerIndex); if (pointerId == this.mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. const newPointerIndex: number = pointerIndex == 0 ? 1 : 0; this.mLastMotionY = Math.floor(ev.getY(newPointerIndex)); this.mActivePointerId = ev.getPointerId(newPointerIndex); if (this.mVelocityTracker != null) { this.mVelocityTracker.clear(); } } } onGenericMotionEvent(event: MotionEvent): boolean { if (event.isPointerEvent()) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: { if (!this.mIsBeingDragged) { const vscroll: number = event.getAxisValue(MotionEvent.AXIS_VSCROLL); if (vscroll != 0) { const delta: number = Math.floor((vscroll * this.getVerticalScrollFactor())); const range: number = this.getScrollRange(); let oldScrollY: number = this.mScrollY; let newScrollY: number = oldScrollY - delta; if (newScrollY < 0) { newScrollY = 0; } else if (newScrollY > range) { newScrollY = range; } if (newScrollY != oldScrollY) { super.scrollTo(this.mScrollX, newScrollY); return true; } } } } } } return super.onGenericMotionEvent(event); } protected onOverScrolled(scrollX: number, scrollY: number, clampedX: boolean, clampedY: boolean): void { // Treat animating scrolls differently; see #computeScroll() for why. if (!this.mScroller.isFinished()) { const oldX: number = this.mScrollX; const oldY: number = this.mScrollY; this.mScrollX = scrollX; this.mScrollY = scrollY; this.invalidateParentIfNeeded(); this.onScrollChanged(this.mScrollX, this.mScrollY, oldX, oldY); if (clampedY) { this.mScroller.springBack(this.mScrollX, this.mScrollY, 0, 0, 0, this.getScrollRange()); } } else { super.scrollTo(scrollX, scrollY); } this.awakenScrollBars(); } // performAccessibilityAction(action:number, arguments:Bundle):boolean { // if (super.performAccessibilityAction(action, arguments)) { // return true; // } // if (!this.isEnabled()) { // return false; // } // switch(action) { // case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: // { // const viewportHeight:number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop; // const targetScrollY:number = Math.min(this.mScrollY + viewportHeight, this.getScrollRange()); // if (targetScrollY != this.mScrollY) { // this.smoothScrollTo(0, targetScrollY); // return true; // } // } // return false; // case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: // { // const viewportHeight:number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop; // const targetScrollY:number = Math.max(this.mScrollY - viewportHeight, 0); // if (targetScrollY != this.mScrollY) { // this.smoothScrollTo(0, targetScrollY); // return true; // } // } // return false; // } // return false; // } // // onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void { // super.onInitializeAccessibilityNodeInfo(info); // info.setClassName(ScrollView.class.getName()); // if (this.isEnabled()) { // const scrollRange:number = this.getScrollRange(); // if (scrollRange > 0) { // info.setScrollable(true); // if (this.mScrollY > 0) { // info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); // } // if (this.mScrollY < scrollRange) { // info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); // } // } // } // } // // onInitializeAccessibilityEvent(event:AccessibilityEvent):void { // super.onInitializeAccessibilityEvent(event); // event.setClassName(ScrollView.class.getName()); // const scrollable:boolean = this.getScrollRange() > 0; // event.setScrollable(scrollable); // event.setScrollX(this.mScrollX); // event.setScrollY(this.mScrollY); // event.setMaxScrollX(this.mScrollX); // event.setMaxScrollY(this.getScrollRange()); // } private getScrollRange(): number { let scrollRange: number = 0; if (this.getChildCount() > 0) { let child: View = this.getChildAt(0); scrollRange = Math.max(0, child.getHeight() - (this.getHeight() - this.mPaddingBottom - this.mPaddingTop)); } return scrollRange; } /** * <p> * Finds the next focusable component that fits in the specified bounds. * </p> * * @param topFocus look for a candidate is the one at the top of the bounds * if topFocus is true, or at the bottom of the bounds if topFocus is * false * @param top the top offset of the bounds in which a focusable must be * found * @param bottom the bottom offset of the bounds in which a focusable must * be found * @return the next focusable component in the bounds or null if none can * be found */ private findFocusableViewInBounds(topFocus: boolean, top: number, bottom: number): View { let focusables: List<View> = this.getFocusables(View.FOCUS_FORWARD); let focusCandidate: View = null; /* * A fully contained focusable is one where its top is below the bound's * top, and its bottom is above the bound's bottom. A partially * contained focusable is one where some part of it is within the * bounds, but it also has some part that is not within bounds. A fully contained * focusable is preferred to a partially contained focusable. */ let foundFullyContainedFocusable: boolean = false; let count: number = focusables.size(); for (let i: number = 0; i < count; i++) { let view: View = focusables.get(i); let viewTop: number = view.getTop(); let viewBottom: number = view.getBottom(); if (top < viewBottom && viewTop < bottom) { /* * the focusable is in the target area, it is a candidate for * focusing */ const viewIsFullyContained: boolean = (top < viewTop) && (viewBottom < bottom); if (focusCandidate == null) { /* No candidate, take this one */ focusCandidate = view; foundFullyContainedFocusable = viewIsFullyContained; } else { const viewIsCloserToBoundary: boolean = (topFocus && viewTop < focusCandidate.getTop()) || (!topFocus && viewBottom > focusCandidate.getBottom()); if (foundFullyContainedFocusable) { if (viewIsFullyContained && viewIsCloserToBoundary) { /* * We're dealing with only fully contained views, so * it has to be closer to the boundary to beat our * candidate */ focusCandidate = view; } } else { if (viewIsFullyContained) { /* Any fully contained view beats a partially contained view */ focusCandidate = view; foundFullyContainedFocusable = true; } else if (viewIsCloserToBoundary) { /* * Partially contained view beats another partially * contained view if it's closer */ focusCandidate = view; } } } } } return focusCandidate; } /** * <p>Handles scrolling in response to a "page up/down" shortcut press. This * method will scroll the view by one page up or down and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go one page up or * {@link android.view.View#FOCUS_DOWN} to go one page down * @return true if the key event is consumed by this method, false otherwise */ pageScroll(direction: number): boolean { let down: boolean = direction == View.FOCUS_DOWN; let height: number = this.getHeight(); if (down) { this.mTempRect.top = this.getScrollY() + height; let count: number = this.getChildCount(); if (count > 0) { let view: View = this.getChildAt(count - 1); if (this.mTempRect.top + height > view.getBottom()) { this.mTempRect.top = view.getBottom() - height; } } } else { this.mTempRect.top = this.getScrollY() - height; if (this.mTempRect.top < 0) { this.mTempRect.top = 0; } } this.mTempRect.bottom = this.mTempRect.top + height; return this.scrollAndFocus(direction, this.mTempRect.top, this.mTempRect.bottom); } /** * <p>Handles scrolling in response to a "home/end" shortcut press. This * method will scroll the view to the top or bottom and give the focus * to the topmost/bottommost component in the new visible area. If no * component is a good candidate for focus, this scrollview reclaims the * focus.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go the top of the view or * {@link android.view.View#FOCUS_DOWN} to go the bottom * @return true if the key event is consumed by this method, false otherwise */ fullScroll(direction: number): boolean { let down: boolean = direction == View.FOCUS_DOWN; let height: number = this.getHeight(); this.mTempRect.top = 0; this.mTempRect.bottom = height; if (down) { let count: number = this.getChildCount(); if (count > 0) { let view: View = this.getChildAt(count - 1); this.mTempRect.bottom = view.getBottom() + this.mPaddingBottom; this.mTempRect.top = this.mTempRect.bottom - height; } } return this.scrollAndFocus(direction, this.mTempRect.top, this.mTempRect.bottom); } /** * <p>Scrolls the view to make the area defined by <code>top</code> and * <code>bottom</code> visible. This method attempts to give the focus * to a component visible in this area. If no component can be focused in * the new visible area, the focus is reclaimed by this ScrollView.</p> * * @param direction the scroll direction: {@link android.view.View#FOCUS_UP} * to go upward, {@link android.view.View#FOCUS_DOWN} to downward * @param top the top offset of the new area to be made visible * @param bottom the bottom offset of the new area to be made visible * @return true if the key event is consumed by this method, false otherwise */ private scrollAndFocus(direction: number, top: number, bottom: number): boolean { let handled: boolean = true; let height: number = this.getHeight(); let containerTop: number = this.getScrollY(); let containerBottom: number = containerTop + height; let up: boolean = direction == View.FOCUS_UP; let newFocused: View = this.findFocusableViewInBounds(up, top, bottom); if (newFocused == null) { newFocused = this; } if (top >= containerTop && bottom <= containerBottom) { handled = false; } else { let delta: number = up ? (top - containerTop) : (bottom - containerBottom); this.doScrollY(delta); } if (newFocused != this.findFocus()) newFocused.requestFocus(direction); return handled; } /** * Handle scrolling in response to an up or down arrow click. * * @param direction The direction corresponding to the arrow key that was * pressed * @return True if we consumed the event, false otherwise */ arrowScroll(direction: number): boolean { let currentFocused: View = this.findFocus(); if (currentFocused == this) currentFocused = null; let nextFocused: View = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); const maxJump: number = this.getMaxScrollAmount(); if (nextFocused != null && this.isWithinDeltaOfScreen(nextFocused, maxJump, this.getHeight())) { nextFocused.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(nextFocused, this.mTempRect); let scrollDelta: number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); this.doScrollY(scrollDelta); nextFocused.requestFocus(direction); } else { // no new focus let scrollDelta: number = maxJump; if (direction == View.FOCUS_UP && this.getScrollY() < scrollDelta) { scrollDelta = this.getScrollY(); } else if (direction == View.FOCUS_DOWN) { if (this.getChildCount() > 0) { let daBottom: number = this.getChildAt(0).getBottom(); let screenBottom: number = this.getScrollY() + this.getHeight() - this.mPaddingBottom; if (daBottom - screenBottom < maxJump) { scrollDelta = daBottom - screenBottom; } } } if (scrollDelta == 0) { return false; } this.doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta); } if (currentFocused != null && currentFocused.isFocused() && this.isOffScreen(currentFocused)) { // previously focused item still has focus and is off screen, give // it up (take it back to ourselves) // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are // sure to // get it) // save const descendantFocusability: number = this.getDescendantFocusability(); this.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); this.requestFocus(); // restore this.setDescendantFocusability(descendantFocusability); } return true; } /** * @return whether the descendant of this scroll view is scrolled off * screen. */ private isOffScreen(descendant: View): boolean { return !this.isWithinDeltaOfScreen(descendant, 0, this.getHeight()); } /** * @return whether the descendant of this scroll view is within delta * pixels of being on the screen. */ private isWithinDeltaOfScreen(descendant: View, delta: number, height: number): boolean { descendant.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(descendant, this.mTempRect); return (this.mTempRect.bottom + delta) >= this.getScrollY() && (this.mTempRect.top - delta) <= (this.getScrollY() + height); } /** * Smooth scroll by a Y delta * * @param delta the number of pixels to scroll by on the Y axis */ private doScrollY(delta: number): void { if (delta != 0) { if (this.mSmoothScrollingEnabled) { this.smoothScrollBy(0, delta); } else { this.scrollBy(0, delta); } } } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param dx the number of pixels to scroll by on the X axis * @param dy the number of pixels to scroll by on the Y axis */ smoothScrollBy(dx: number, dy: number): void { if (this.getChildCount() == 0) { // Nothing to do. return; } let duration: number = AnimationUtils.currentAnimationTimeMillis() - this.mLastScroll; if (duration > ScrollView.ANIMATED_SCROLL_GAP) { const height: number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop; const bottom: number = this.getChildAt(0).getHeight(); const maxY: number = Math.max(0, bottom - height); const scrollY: number = this.mScrollY; dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY; this.mScroller.startScroll(this.mScrollX, scrollY, 0, dy); this.postInvalidateOnAnimation(); } else { if (!this.mScroller.isFinished()) { this.mScroller.abortAnimation(); // if (this.mFlingStrictSpan != null) { // this.mFlingStrictSpan.finish(); // this.mFlingStrictSpan = null; // } } this.scrollBy(dx, dy); } this.mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } /** * Like {@link #scrollTo}, but scroll smoothly instead of immediately. * * @param x the position where to scroll on the X axis * @param y the position where to scroll on the Y axis */ smoothScrollTo(x: number, y: number): void { this.smoothScrollBy(x - this.mScrollX, y - this.mScrollY); } /** * <p>The scroll range of a scroll view is the overall height of all of its * children.</p> */ protected computeVerticalScrollRange(): number { const count: number = this.getChildCount(); const contentHeight: number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop; if (count == 0) { return contentHeight; } let scrollRange: number = this.getChildAt(0).getBottom(); const scrollY: number = this.mScrollY; const overscrollBottom: number = Math.max(0, scrollRange - contentHeight); if (scrollY < 0) { scrollRange -= scrollY; } else if (scrollY > overscrollBottom) { scrollRange += scrollY - overscrollBottom; } return scrollRange; } protected computeVerticalScrollOffset(): number { return Math.max(0, super.computeVerticalScrollOffset()); } protected measureChild(child: View, parentWidthMeasureSpec: number, parentHeightMeasureSpec: number): void { let lp: ViewGroup.LayoutParams = child.getLayoutParams(); let childWidthMeasureSpec: number; let childHeightMeasureSpec: number; childWidthMeasureSpec = ScrollView.getChildMeasureSpec(parentWidthMeasureSpec, this.mPaddingLeft + this.mPaddingRight, lp.width); childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } protected measureChildWithMargins(child: View, parentWidthMeasureSpec: number, widthUsed: number, parentHeightMeasureSpec: number, heightUsed: number): void { const lp: ViewGroup.MarginLayoutParams = <ViewGroup.MarginLayoutParams> child.getLayoutParams(); const childWidthMeasureSpec: number = ScrollView.getChildMeasureSpec(parentWidthMeasureSpec, this.mPaddingLeft + this.mPaddingRight + lp.leftMargin + lp.rightMargin + widthUsed, lp.width); const childHeightMeasureSpec: number = View.MeasureSpec.makeMeasureSpec(lp.topMargin + lp.bottomMargin, View.MeasureSpec.UNSPECIFIED); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } computeScroll(): void { if (this.mScroller.computeScrollOffset()) { // This is called at drawing time by ViewGroup. We don't want to // re-show the scrollbars at this point, which scrollTo will do, // so we replicate most of scrollTo here. // // It's a little odd to call onScrollChanged from inside the drawing. // // It is, except when you remember that computeScroll() is used to // animate scrolling. So unless we want to defer the onScrollChanged() // until the end of the animated scrolling, we don't really have a // choice here. // // I agree. The alternative, which I think would be worse, is to post // something and tell the subclasses later. This is bad because there // will be a window where mScrollX/Y is different from what the app // thinks it is. // let oldX: number = this.mScrollX; let oldY: number = this.mScrollY; let x: number = this.mScroller.getCurrX(); let y: number = this.mScroller.getCurrY(); if (oldX != x || oldY != y) { const range: number = this.getScrollRange(); const overscrollMode: number = this.getOverScrollMode(); const canOverscroll: boolean = overscrollMode == ScrollView.OVER_SCROLL_ALWAYS || (overscrollMode == ScrollView.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0); this.overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range, 0, this.getHeight() / 2, false); this.onScrollChanged(this.mScrollX, this.mScrollY, oldX, oldY); // if (canOverscroll) { // if (y < 0 && oldY >= 0) { // this.mEdgeGlowTop.onAbsorb(Math.floor(this.mScroller.getCurrVelocity())); // } else if (y > range && oldY <= range) { // this.mEdgeGlowBottom.onAbsorb(Math.floor(this.mScroller.getCurrVelocity())); // } // } } if (!this.awakenScrollBars()) { // Keep on drawing until the animation has finished. this.postInvalidateOnAnimation(); } } else { // if (this.mFlingStrictSpan != null) { // this.mFlingStrictSpan.finish(); // this.mFlingStrictSpan = null; // } } } /** * Scrolls the view to the given child. * * @param child the View to scroll to */ private scrollToChild(child: View): void { child.getDrawingRect(this.mTempRect); /* Offset from child's local coordinates to ScrollView coordinates */ this.offsetDescendantRectToMyCoords(child, this.mTempRect); let scrollDelta: number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); if (scrollDelta != 0) { this.scrollBy(0, scrollDelta); } } /** * If rect is off screen, scroll just enough to get it (or at least the * first screen size chunk of it) on screen. * * @param rect The rectangle. * @param immediate True to scroll immediately without animation * @return true if scrolling was performed */ private scrollToChildRect(rect: Rect, immediate: boolean): boolean { const delta: number = this.computeScrollDeltaToGetChildRectOnScreen(rect); const scroll: boolean = delta != 0; if (scroll) { if (immediate) { this.scrollBy(0, delta); } else { this.smoothScrollBy(0, delta); } } return scroll; } /** * Compute the amount to scroll in the Y direction in order to get * a rectangle completely on the screen (or, if taller than the screen, * at least the first screen size chunk of it). * * @param rect The rect. * @return The scroll delta. */ protected computeScrollDeltaToGetChildRectOnScreen(rect: Rect): number { if (this.getChildCount() == 0) return 0; let height: number = this.getHeight(); let screenTop: number = this.getScrollY(); let screenBottom: number = screenTop + height; let fadingEdge: number = this.getVerticalFadingEdgeLength(); // leave room for top fading edge as long as rect isn't at very top if (rect.top > 0) { screenTop += fadingEdge; } // leave room for bottom fading edge as long as rect isn't at very bottom if (rect.bottom < this.getChildAt(0).getHeight()) { screenBottom -= fadingEdge; } let scrollYDelta: number = 0; if (rect.bottom > screenBottom && rect.top > screenTop) { if (rect.height() > height) { // just enough to get screen size chunk on scrollYDelta += (rect.top - screenTop); } else { // get entire rect at bottom of screen scrollYDelta += (rect.bottom - screenBottom); } // make sure we aren't scrolling beyond the end of our content let bottom: number = this.getChildAt(0).getBottom(); let distanceToBottom: number = bottom - screenBottom; scrollYDelta = Math.min(scrollYDelta, distanceToBottom); } else if (rect.top < screenTop && rect.bottom < screenBottom) { if (rect.height() > height) { // screen size chunk scrollYDelta -= (screenBottom - rect.bottom); } else { // entire rect at top scrollYDelta -= (screenTop - rect.top); } // make sure we aren't scrolling any further than the top our content scrollYDelta = Math.max(scrollYDelta, -this.getScrollY()); } return scrollYDelta; } requestChildFocus(child: View, focused: View): void { if (!this.mIsLayoutDirty) { this.scrollToChild(focused); } else { // The child may not be laid out yet, we can't compute the scroll yet this.mChildToScrollTo = focused; } super.requestChildFocus(child, focused); } /** * When looking for focus in children of a scroll view, need to be a little * more careful not to give focus to something that is scrolled off screen. * * This is more expensive than the default {@link android.view.ViewGroup} * implementation, otherwise this behavior might have been made the default. */ protected onRequestFocusInDescendants(direction: number, previouslyFocusedRect: Rect): boolean { // (ugh). if (direction == View.FOCUS_FORWARD) { direction = View.FOCUS_DOWN; } else if (direction == View.FOCUS_BACKWARD) { direction = View.FOCUS_UP; } const nextFocus: View = previouslyFocusedRect == null ? FocusFinder.getInstance().findNextFocus(this, null, direction) : FocusFinder.getInstance().findNextFocusFromRect(this, previouslyFocusedRect, direction); if (nextFocus == null) { return false; } if (this.isOffScreen(nextFocus)) { return false; } return nextFocus.requestFocus(direction, previouslyFocusedRect); } requestChildRectangleOnScreen(child: View, rectangle: Rect, immediate: boolean): boolean { // offset into coordinate space of this scroll view rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY()); return this.scrollToChildRect(rectangle, immediate); } requestLayout(): void { this.mIsLayoutDirty = true; super.requestLayout(); } // protected onDetachedFromWindow():void { // super.onDetachedFromWindow(); // if (this.mScrollStrictSpan != null) { // this.mScrollStrictSpan.finish(); // this.mScrollStrictSpan = null; // } // if (this.mFlingStrictSpan != null) { // this.mFlingStrictSpan.finish(); // this.mFlingStrictSpan = null; // } // } protected onLayout(changed: boolean, l: number, t: number, r: number, b: number): void { super.onLayout(changed, l, t, r, b); this.mIsLayoutDirty = false; // Give a child focus if it needs it if (this.mChildToScrollTo != null && ScrollView.isViewDescendantOf(this.mChildToScrollTo, this)) { this.scrollToChild(this.mChildToScrollTo); } this.mChildToScrollTo = null; if (!this.isLaidOut()) { // if (this.mSavedState != null) { // this.mScrollY = this.mSavedState.scrollPosition; // this.mSavedState = null; // } // mScrollY default value is "0" const childHeight: number = (this.getChildCount() > 0) ? this.getChildAt(0).getMeasuredHeight() : 0; const scrollRange: number = Math.max(0, childHeight - (b - t - this.mPaddingBottom - this.mPaddingTop)); // Don't forget to clamp if (this.mScrollY > scrollRange) { this.mScrollY = scrollRange; } else if (this.mScrollY < 0) { this.mScrollY = 0; } } // Calling this with the present values causes it to re-claim them this.scrollTo(this.mScrollX, this.mScrollY); } protected onSizeChanged(w: number, h: number, oldw: number, oldh: number): void { super.onSizeChanged(w, h, oldw, oldh); let currentFocused: View = this.findFocus(); if (null == currentFocused || this == currentFocused) return; // view visible with the new screen height. if (this.isWithinDeltaOfScreen(currentFocused, 0, oldh)) { currentFocused.getDrawingRect(this.mTempRect); this.offsetDescendantRectToMyCoords(currentFocused, this.mTempRect); let scrollDelta: number = this.computeScrollDeltaToGetChildRectOnScreen(this.mTempRect); this.doScrollY(scrollDelta); } } /** * Return true if child is a descendant of parent, (or equal to the parent). */ private static isViewDescendantOf(child: View, parent: View): boolean { if (child == parent) { return true; } const theParent: ViewParent = child.getParent(); return (theParent instanceof ViewGroup) && ScrollView.isViewDescendantOf(<View> theParent, parent); } /** * Fling the scroll view * * @param velocityY The initial velocity in the Y direction. Positive * numbers mean that the finger/cursor is moving down the screen, * which means we want to scroll towards the top. */ fling(velocityY: number): void { if (this.getChildCount() > 0) { let height: number = this.getHeight() - this.mPaddingBottom - this.mPaddingTop; let bottom: number = this.getChildAt(0).getHeight(); this.mScroller.fling(this.mScrollX, this.mScrollY, 0, velocityY, 0, 0, 0, Math.max(0, bottom - height), 0, this.mOverflingDistance); // if (this.mFlingStrictSpan == null) { // this.mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling"); // } this.postInvalidateOnAnimation(); } } private endDrag(): void { this.mIsBeingDragged = false; this.recycleVelocityTracker(); // if (this.mEdgeGlowTop != null) { // this.mEdgeGlowTop.onRelease(); // this.mEdgeGlowBottom.onRelease(); // } // if (this.mScrollStrictSpan != null) { // this.mScrollStrictSpan.finish(); // this.mScrollStrictSpan = null; // } } /** * {@inheritDoc} * * <p>This version also clamps the scrolling to the bounds of our child. */ scrollTo(x: number, y: number): void { // we rely on the fact the View.scrollBy calls scrollTo. if (this.getChildCount() > 0) { let child: View = this.getChildAt(0); x = ScrollView.clamp(x, this.getWidth() - this.mPaddingRight - this.mPaddingLeft, child.getWidth()); y = ScrollView.clamp(y, this.getHeight() - this.mPaddingBottom - this.mPaddingTop, child.getHeight()); if (x != this.mScrollX || y != this.mScrollY) { super.scrollTo(x, y); } } } // setOverScrollMode(mode:number):void { // if (mode != ScrollView.OVER_SCROLL_NEVER) { // if (this.mEdgeGlowTop == null) { // let context = this.getContext(); // this.mEdgeGlowTop = new EdgeEffect(context); // this.mEdgeGlowBottom = new EdgeEffect(context); // } // } else { // this.mEdgeGlowTop = null; // this.mEdgeGlowBottom = null; // } // super.setOverScrollMode(mode); // } draw(canvas: Canvas): void { super.draw(canvas); // if (this.mEdgeGlowTop != null) { // const scrollY:number = this.mScrollY; // if (!this.mEdgeGlowTop.isFinished()) { // const restoreCount:number = canvas.save(); // const width:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; // canvas.translate(this.mPaddingLeft, Math.min(0, scrollY)); // this.mEdgeGlowTop.setSize(width, this.getHeight()); // if (this.mEdgeGlowTop.draw(canvas)) { // this.postInvalidateOnAnimation(); // } // canvas.restoreToCount(restoreCount); // } // if (!this.mEdgeGlowBottom.isFinished()) { // const restoreCount:number = canvas.save(); // const width:number = this.getWidth() - this.mPaddingLeft - this.mPaddingRight; // const height:number = this.getHeight(); // canvas.translate(-width + this.mPaddingLeft, Math.max(this.getScrollRange(), scrollY) + height); // canvas.rotate(180, width, 0); // this.mEdgeGlowBottom.setSize(width, height); // if (this.mEdgeGlowBottom.draw(canvas)) { // this.postInvalidateOnAnimation(); // } // canvas.restoreToCount(restoreCount); // } // } } private static clamp(n: number, my: number, child: number): number { if (my >= child || n < 0) { /* my >= child is this case: * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * or * |--------------- me ---------------| * |------ child ------| * * n < 0 is this case: * |------ me ------| * |-------- child --------| * |-- mScrollX --| */ return 0; } if ((my + n) > child) { /* this case: * |------ me ------| * |------ child ------| * |-- mScrollX --| */ return child - my; } return n; } // protected onRestoreInstanceState(state:Parcelable):void { // if (this.mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // // Some old apps reused IDs in ways they shouldn't have. // // Don't break them, but they don't get scroll state restoration. // super.onRestoreInstanceState(state); // return; // } // let ss:ScrollView.SavedState = <ScrollView.SavedState> state; // super.onRestoreInstanceState(ss.getSuperState()); // this.mSavedState = ss; // this.requestLayout(); // } // // protected onSaveInstanceState():Parcelable { // if (this.mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // // Don't break them, but they don't get scroll state restoration. // return super.onSaveInstanceState(); // } // let superState:Parcelable = super.onSaveInstanceState(); // let ss:ScrollView.SavedState = new ScrollView.SavedState(superState); // ss.scrollPosition = this.mScrollY; // return ss; // } } // export module ScrollView{ // export class SavedState extends View.BaseSavedState { // // scrollPosition:number = 0; // // constructor( superState:Parcelable) { // super(superState); // } // // constructor( source:Parcel) { // super(source); // this.scrollPosition = source.readInt(); // } // // writeToParcel(dest:Parcel, flags:number):void { // super.writeToParcel(dest, flags); // dest.writeInt(this.scrollPosition); // } // // toString():string { // return "HorizontalScrollView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " scrollPosition=" + this.scrollPosition + "}"; // } // // static CREATOR:Parcelable.Creator<SavedState> = (()=>{ // const inner_this=this; // class _Inner extends Parcelable.Creator<SavedState> { // // createFromParcel(_in:Parcel):SavedState { // return new SavedState(_in); // } // // newArray(size:number):SavedState[] { // return new Array<SavedState>(size); // } // } // return new _Inner(); // })(); // } // } }
the_stack
import { store } from "@graphprotocol/graph-ts"; // Import event types from the registrar contract ABIs import { BondingManager, WithdrawStake, Bond, Unbond, Rebond, WithdrawFees, Reward, TranscoderSlashed, TranscoderUpdate, TranscoderActivated, TranscoderDeactivated, EarningsClaimed, ParameterUpdate, } from "../types/BondingManager/BondingManager"; import { BondEvent, Delegator, EarningsClaimedEvent, ParameterUpdateEvent, Pool, Protocol, RebondEvent, RewardEvent, Transaction, Transcoder, TranscoderActivatedEvent, TranscoderDeactivatedEvent, TranscoderSlashedEvent, TranscoderUpdateEvent, UnbondEvent, UnbondingLock, WithdrawFeesEvent, WithdrawStakeEvent, } from "../types/schema"; import { makeUnbondingLockId, makeEventId, EMPTY_ADDRESS, convertToDecimal, createOrLoadTranscoder, createOrLoadDelegator, createOrLoadRound, makePoolId, MAXIMUM_VALUE_UINT256, createOrLoadProtocol, } from "../../utils/helpers"; export function bond(event: Bond): void { let bondingManager = BondingManager.bind(event.address); let delegateData = bondingManager.getDelegator(event.params.newDelegate); let delegatorData = bondingManager.getDelegator(event.params.delegator); let round = createOrLoadRound(event.block.number); let transcoder = createOrLoadTranscoder(event.params.newDelegate.toHex()); let delegate = createOrLoadDelegator(event.params.newDelegate.toHex()); let delegator = createOrLoadDelegator(event.params.delegator.toHex()); let protocol = Protocol.load("0"); // If self delegating, set status and assign reference to self if (event.params.delegator.toHex() == event.params.newDelegate.toHex()) { transcoder.status = "Registered"; transcoder.delegator = event.params.delegator.toHex(); } // Changing delegate if ( event.params.oldDelegate.toHex() != EMPTY_ADDRESS.toHex() && event.params.oldDelegate.toHex() != event.params.newDelegate.toHex() ) { let oldTranscoder = Transcoder.load(event.params.oldDelegate.toHex()); let oldDelegate = Delegator.load(event.params.oldDelegate.toHex()); let oldDelegateData = bondingManager.getDelegator(event.params.oldDelegate); // if previous delegate was itself, set status and unassign reference to self if (event.params.oldDelegate.toHex() == event.params.delegator.toHex()) { oldTranscoder.status = "NotRegistered"; oldTranscoder.delegator = null; } oldTranscoder.totalStake = convertToDecimal(oldDelegateData.value3); oldDelegate.delegatedAmount = convertToDecimal(oldDelegateData.value3); oldDelegate.save(); oldTranscoder.save(); // keep track of how much stake moved during this round. round.movedStake = round.movedStake.plus( convertToDecimal(delegatorData.value0).minus( convertToDecimal(event.params.additionalAmount) ) ); // keep track of how much new stake was introduced this round round.newStake = round.newStake.plus( convertToDecimal(event.params.additionalAmount) ); round.save(); } transcoder.totalStake = convertToDecimal(delegateData.value3); delegate.delegatedAmount = convertToDecimal(delegateData.value3); delegator.delegate = event.params.newDelegate.toHex(); delegator.lastClaimRound = round.id; delegator.bondedAmount = convertToDecimal(event.params.bondedAmount); delegator.fees = convertToDecimal(delegatorData.value1); delegator.startRound = delegatorData.value4; delegator.principal = delegator.principal.plus( convertToDecimal(event.params.additionalAmount) ); delegate.save(); delegator.save(); transcoder.save(); protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let bondEvent = new BondEvent( makeEventId(event.transaction.hash, event.logIndex) ); bondEvent.transaction = event.transaction.hash.toHex(); bondEvent.timestamp = event.block.timestamp.toI32(); bondEvent.round = round.id; bondEvent.newDelegate = event.params.newDelegate.toHex(); bondEvent.oldDelegate = event.params.oldDelegate.toHex(); bondEvent.delegator = event.params.delegator.toHex(); bondEvent.bondedAmount = convertToDecimal(event.params.bondedAmount); bondEvent.additionalAmount = convertToDecimal(event.params.additionalAmount); bondEvent.save(); } // Handler for Unbond events export function unbond(event: Unbond): void { let bondingManager = BondingManager.bind(event.address); let uniqueUnbondingLockId = makeUnbondingLockId( event.params.delegator, event.params.unbondingLockId ); let withdrawRound = event.params.withdrawRound; let amount = convertToDecimal(event.params.amount); let delegator = Delegator.load(event.params.delegator.toHex()); let delegateData = bondingManager.getDelegator(event.params.delegate); let round = createOrLoadRound(event.block.number); let transcoder = createOrLoadTranscoder(event.params.delegate.toHex()); let delegate = createOrLoadDelegator(event.params.delegate.toHex()); let unbondingLock = UnbondingLock.load(uniqueUnbondingLockId) || new UnbondingLock(uniqueUnbondingLockId); let protocol = Protocol.load("0"); delegate.delegatedAmount = convertToDecimal(delegateData.value3); transcoder.totalStake = convertToDecimal(delegateData.value3); let delegatorData = bondingManager.getDelegator(event.params.delegator); delegator.lastClaimRound = round.id; delegator.bondedAmount = convertToDecimal(delegatorData.value0); delegator.fees = convertToDecimal(delegatorData.value1); delegator.startRound = delegatorData.value4; delegator.unbonded = delegator.unbonded.plus( convertToDecimal(event.params.amount) ); // Delegator no longer delegated to anyone if it does not have a bonded amount // so remove it from delegate if (delegatorData.value0.isZero()) { // If unbonding from self and no longer has a bonded amount // update transcoder status and delegator if (event.params.delegator.toHex() == event.params.delegate.toHex()) { transcoder.status = "NotRegistered"; transcoder.delegator = null; } // Update delegator's delegate delegator.delegate = null; } unbondingLock.unbondingLockId = event.params.unbondingLockId.toI32(); unbondingLock.delegator = event.params.delegator.toHex(); unbondingLock.delegate = event.params.delegate.toHex(); unbondingLock.withdrawRound = withdrawRound; unbondingLock.amount = amount; // Apply store updates delegate.save(); transcoder.save(); unbondingLock.save(); delegator.save(); protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let unbondEvent = new UnbondEvent( makeEventId(event.transaction.hash, event.logIndex) ); unbondEvent.transaction = event.transaction.hash.toHex(); unbondEvent.timestamp = event.block.timestamp.toI32(); unbondEvent.round = round.id; unbondEvent.amount = amount; unbondEvent.withdrawRound = unbondingLock.withdrawRound; unbondEvent.unbondingLockId = event.params.unbondingLockId.toI32(); unbondEvent.delegate = event.params.delegate.toHex(); unbondEvent.delegator = delegator.id; unbondEvent.save(); } // Handler for Rebond events export function rebond(event: Rebond): void { let bondingManager = BondingManager.bind(event.address); let uniqueUnbondingLockId = makeUnbondingLockId( event.params.delegator, event.params.unbondingLockId ); let round = createOrLoadRound(event.block.number); let transcoder = Transcoder.load(event.params.delegate.toHex()); let delegate = Delegator.load(event.params.delegate.toHex()); let delegator = Delegator.load(event.params.delegator.toHex()); let delegateData = bondingManager.getDelegator(event.params.delegate); let protocol = Protocol.load("0"); // If rebonding from unbonded if (!delegator.delegate) { // If self-bonding then update transcoder status if (event.params.delegate.toHex() == event.params.delegator.toHex()) { transcoder.status = "Registered"; transcoder.delegator = event.params.delegator.toHex(); } } // update delegator let delegatorData = bondingManager.getDelegator(event.params.delegator); delegator.delegate = event.params.delegate.toHex(); delegator.startRound = delegatorData.value4; delegator.lastClaimRound = round.id; delegator.bondedAmount = convertToDecimal(delegatorData.value0); delegator.fees = convertToDecimal(delegatorData.value1); delegator.unbonded = delegator.unbonded.minus( convertToDecimal(event.params.amount) ); // update delegate delegate.delegatedAmount = convertToDecimal(delegateData.value3); transcoder.totalStake = convertToDecimal(delegateData.value3); // Apply store updates delegate.save(); transcoder.save(); delegator.save(); protocol.save(); store.remove("UnbondingLock", uniqueUnbondingLockId); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let rebondEvent = new RebondEvent( makeEventId(event.transaction.hash, event.logIndex) ); rebondEvent.transaction = event.transaction.hash.toHex(); rebondEvent.timestamp = event.block.timestamp.toI32(); rebondEvent.round = round.id; rebondEvent.delegator = delegator.id; rebondEvent.delegate = delegate.id; rebondEvent.amount = convertToDecimal(event.params.amount); rebondEvent.unbondingLockId = event.params.unbondingLockId.toI32(); rebondEvent.save(); } // Handler for WithdrawStake events export function withdrawStake(event: WithdrawStake): void { let round = createOrLoadRound(event.block.number); let uniqueUnbondingLockId = makeUnbondingLockId( event.params.delegator, event.params.unbondingLockId ); store.remove("UnbondingLock", uniqueUnbondingLockId); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let withdrawStakeEvent = new WithdrawStakeEvent( makeEventId(event.transaction.hash, event.logIndex) ); withdrawStakeEvent.transaction = event.transaction.hash.toHex(); withdrawStakeEvent.timestamp = event.block.timestamp.toI32(); withdrawStakeEvent.round = round.id; withdrawStakeEvent.amount = convertToDecimal(event.params.amount); withdrawStakeEvent.unbondingLockId = event.params.unbondingLockId.toI32(); withdrawStakeEvent.delegator = event.params.delegator.toHex(); withdrawStakeEvent.save(); } export function withdrawFees(event: WithdrawFees): void { let bondingManager = BondingManager.bind(event.address); let delegator = Delegator.load(event.params.delegator.toHex()); let delegatorData = bondingManager.getDelegator(event.params.delegator); let round = createOrLoadRound(event.block.number); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let withdrawFeesEvent = new WithdrawFeesEvent( makeEventId(event.transaction.hash, event.logIndex) ); withdrawFeesEvent.transaction = event.transaction.hash.toHex(); withdrawFeesEvent.timestamp = event.block.timestamp.toI32(); withdrawFeesEvent.round = round.id; withdrawFeesEvent.amount = delegator.fees; withdrawFeesEvent.delegator = event.params.delegator.toHex(); withdrawFeesEvent.save(); delegator.bondedAmount = convertToDecimal(delegatorData.value0); delegator.fees = convertToDecimal(delegatorData.value1); delegator.withdrawnFees = delegator.withdrawnFees.plus( withdrawFeesEvent.amount ); delegator.lastClaimRound = round.id; delegator.save(); } export function parameterUpdate(event: ParameterUpdate): void { let bondingManager = BondingManager.bind(event.address); let protocol = createOrLoadProtocol(); if (event.params.param == "unbondingPeriod") { protocol.unbondingPeriod = bondingManager.unbondingPeriod(); } if (event.params.param == "numActiveTranscoders") { protocol.numActiveTranscoders = bondingManager .getTranscoderPoolMaxSize() .toI32(); } if (event.params.param == "maxEarningsClaimsRounds") { protocol.maxEarningsClaimsRounds = bondingManager .maxEarningsClaimsRounds() .toI32(); } protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let parameterUpdateEvent = new ParameterUpdateEvent( makeEventId(event.transaction.hash, event.logIndex) ); parameterUpdateEvent.transaction = event.transaction.hash.toHex(); parameterUpdateEvent.timestamp = event.block.timestamp.toI32(); parameterUpdateEvent.param = event.params.param; parameterUpdateEvent.round = protocol.currentRound; parameterUpdateEvent.save(); } // Handler for Reward events export function reward(event: Reward): void { let transcoder = Transcoder.load(event.params.transcoder.toHex()); let delegate = Delegator.load(event.params.transcoder.toHex()); let round = createOrLoadRound(event.block.number); let poolId = makePoolId(event.params.transcoder.toHex(), round.id); let pool = Pool.load(poolId); let protocol = Protocol.load("0"); delegate.delegatedAmount = delegate.delegatedAmount.plus( convertToDecimal(event.params.amount) ); pool.rewardTokens = convertToDecimal(event.params.amount); pool.feeShare = transcoder.feeShare; pool.rewardCut = transcoder.rewardCut; transcoder.totalStake = transcoder.totalStake.plus( convertToDecimal(event.params.amount) ); transcoder.lastRewardRound = round.id; transcoder.save(); delegate.save(); pool.save(); protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let rewardEvent = new RewardEvent( makeEventId(event.transaction.hash, event.logIndex) ); rewardEvent.transaction = event.transaction.hash.toHex(); rewardEvent.timestamp = event.block.timestamp.toI32(); rewardEvent.round = round.id; rewardEvent.rewardTokens = convertToDecimal(event.params.amount); rewardEvent.delegate = event.params.transcoder.toHex(); rewardEvent.save(); } // Handler for TranscoderSlashed events export function transcoderSlashed(event: TranscoderSlashed): void { let transcoder = Transcoder.load(event.params.transcoder.toHex()); let bondingManager = BondingManager.bind(event.address); let round = createOrLoadRound(event.block.number); let delegateData = bondingManager.getDelegator(event.params.transcoder); // Update transcoder total stake transcoder.totalStake = convertToDecimal(delegateData.value3); // Apply store updates transcoder.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let transcoderSlashedEvent = new TranscoderSlashedEvent( makeEventId(event.transaction.hash, event.logIndex) ); transcoderSlashedEvent.transaction = event.transaction.hash.toHex(); transcoderSlashedEvent.timestamp = event.block.timestamp.toI32(); transcoderSlashedEvent.round = round.id; transcoderSlashedEvent.delegate = event.params.transcoder.toHex(); transcoderSlashedEvent.save(); } export function transcoderUpdate(event: TranscoderUpdate): void { let round = createOrLoadRound(event.block.number); let transcoder = createOrLoadTranscoder(event.params.transcoder.toHex()); transcoder.rewardCut = event.params.rewardCut; transcoder.feeShare = event.params.feeShare; transcoder.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let transcoderUpdateEvent = new TranscoderUpdateEvent( makeEventId(event.transaction.hash, event.logIndex) ); transcoderUpdateEvent.transaction = event.transaction.hash.toHex(); transcoderUpdateEvent.timestamp = event.block.timestamp.toI32(); transcoderUpdateEvent.round = round.id; transcoderUpdateEvent.rewardCut = event.params.rewardCut; transcoderUpdateEvent.feeShare = event.params.feeShare; transcoderUpdateEvent.delegate = event.params.transcoder.toHex(); transcoderUpdateEvent.save(); } export function transcoderActivated(event: TranscoderActivated): void { let round = createOrLoadRound(event.block.number); let transcoder = createOrLoadTranscoder(event.params.transcoder.toHex()); let protocol = Protocol.load("0"); transcoder.lastActiveStakeUpdateRound = event.params.activationRound; transcoder.activationRound = event.params.activationRound; transcoder.deactivationRound = MAXIMUM_VALUE_UINT256; transcoder.save(); // Add transcoder to list of transcoders pending activation let pendingActivation = protocol.pendingActivation; pendingActivation.push(event.params.transcoder.toHex()); protocol.pendingActivation = pendingActivation; protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let transcoderActivatedEvent = new TranscoderActivatedEvent( makeEventId(event.transaction.hash, event.logIndex) ); transcoderActivatedEvent.transaction = event.transaction.hash.toHex(); transcoderActivatedEvent.timestamp = event.block.timestamp.toI32(); transcoderActivatedEvent.round = round.id; transcoderActivatedEvent.activationRound = event.params.activationRound; transcoderActivatedEvent.delegate = event.params.transcoder.toHex(); transcoderActivatedEvent.save(); } export function transcoderDeactivated(event: TranscoderDeactivated): void { let transcoder = Transcoder.load(event.params.transcoder.toHex()); let round = createOrLoadRound(event.block.number); let protocol = Protocol.load("0"); transcoder.deactivationRound = event.params.deactivationRound; transcoder.save(); // Add transcoder to list of transcoders pending deactivation let pendingDeactivation = protocol.pendingDeactivation; pendingDeactivation.push(event.params.transcoder.toHex()); protocol.pendingDeactivation = pendingDeactivation; protocol.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let transcoderDeactivatedEvent = new TranscoderDeactivatedEvent( makeEventId(event.transaction.hash, event.logIndex) ); transcoderDeactivatedEvent.transaction = event.transaction.hash.toHex(); transcoderDeactivatedEvent.timestamp = event.block.timestamp.toI32(); transcoderDeactivatedEvent.round = round.id; transcoderDeactivatedEvent.deactivationRound = event.params.deactivationRound; transcoderDeactivatedEvent.delegate = event.params.transcoder.toHex(); transcoderDeactivatedEvent.save(); } export function earningsClaimed(event: EarningsClaimed): void { let round = createOrLoadRound(event.block.number); let delegator = createOrLoadDelegator(event.params.delegator.toHex()); delegator.lastClaimRound = event.params.endRound.toString(); delegator.bondedAmount = delegator.bondedAmount.plus( convertToDecimal(event.params.rewards) ); delegator.fees = delegator.fees.plus(convertToDecimal(event.params.fees)); delegator.save(); let tx = Transaction.load(event.transaction.hash.toHex()) || new Transaction(event.transaction.hash.toHex()); tx.blockNumber = event.block.number; tx.gasUsed = event.transaction.gasUsed; tx.gasPrice = event.transaction.gasPrice; tx.timestamp = event.block.timestamp.toI32(); tx.from = event.transaction.from.toHex(); tx.to = event.transaction.to.toHex(); tx.save(); let earningsClaimedEvent = new EarningsClaimedEvent( makeEventId(event.transaction.hash, event.logIndex) ); earningsClaimedEvent.transaction = event.transaction.hash.toHex(); earningsClaimedEvent.timestamp = event.block.timestamp.toI32(); earningsClaimedEvent.round = round.id; earningsClaimedEvent.delegate = event.params.delegate.toHex(); earningsClaimedEvent.delegator = event.params.delegator.toHex(); earningsClaimedEvent.startRound = event.params.startRound; earningsClaimedEvent.endRound = event.params.endRound.toString(); earningsClaimedEvent.rewardTokens = convertToDecimal(event.params.rewards); earningsClaimedEvent.fees = convertToDecimal(event.params.fees); earningsClaimedEvent.save(); }
the_stack
import {getDesiredMultiscaleMeshChunks, getMultiscaleChunksToDraw, MultiscaleMeshManifest} from 'neuroglancer/mesh/multiscale'; import {getFrustrumPlanes, mat4, vec3} from 'neuroglancer/util/geom'; interface MultiscaleChunkResult { lod: number; row: number; renderScale: number; empty: number; } function getDesiredChunkList( manifest: MultiscaleMeshManifest, modelViewProjection: mat4, detailCutoff: number, viewportWidth: number, viewportHeight: number): MultiscaleChunkResult[] { const results: MultiscaleChunkResult[] = []; getDesiredMultiscaleMeshChunks( manifest, modelViewProjection, getFrustrumPlanes(new Float32Array(24), modelViewProjection), detailCutoff, viewportWidth, viewportHeight, (lod, row, renderScale, empty) => { results.push({lod, row, renderScale, empty}); }); return results; } interface MultiscaleChunkDrawResult { lod: number; row: number; renderScale: number; subChunkBegin: number; subChunkEnd: number; } function getDrawChunkList( manifest: MultiscaleMeshManifest, modelViewProjection: mat4, detailCutoff: number, viewportWidth: number, viewportHeight: number, hasChunk: (row: number) => boolean): MultiscaleChunkDrawResult[] { const results: MultiscaleChunkDrawResult[] = []; getMultiscaleChunksToDraw( manifest, modelViewProjection, getFrustrumPlanes(new Float32Array(24), modelViewProjection), detailCutoff, viewportWidth, viewportHeight, (_lod, row, _renderScale) => { return hasChunk(row); }, (lod, row, subChunkBegin, subChunkEnd, renderScale) => { results.push({lod, row, subChunkBegin, subChunkEnd, renderScale}); }); return results; } describe('multiscale', () => { it('getDesiredMultiscaleMeshChunks simple', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(20, 23, -50), clipUpperBound: vec3.fromValues(40, 45, -20), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 0, 0, 0, 0, 1, // row 0, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect( getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight)) .toEqual([{ lod: 1, renderScale: 960, row: 1, empty: 0, }]); expect(getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 800, viewportWidth, viewportHeight)) .toEqual([ { lod: 1, renderScale: 960, row: 1, empty: 0, }, { lod: 0, renderScale: 480, row: 0, empty: 0, } ]); }); it('getDesiredMultiscaleMeshChunks multiple chunks 2 lods', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 1, 0, 0, 0, 0, // row 1, lod 0 0, 1, 0, 0, 0, // row 2, lod 0 1, 1, 0, 0, 0, // row 3, lod 0 0, 0, 1, 0, 0, // row 4, lod 0 1, 0, 1, 0, 0, // row 5, lod 0 0, 1, 1, 0, 0, // row 6, lod 0 1, 1, 1, 0, 0, // row 7, lod 0 0, 0, 0, 0, 8, // row 8, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect( getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 4000, viewportWidth, viewportHeight)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, empty: 0, }, ]); expect( getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, empty: 0, }, { lod: 0, renderScale: 1920, row: 4, empty: 0, }, { lod: 0, renderScale: 1920, row: 5, empty: 0, }, ]); expect(getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 800, viewportWidth, viewportHeight)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, empty: 0, }, { lod: 0, renderScale: 480, row: 0, empty: 0, }, { lod: 0, renderScale: 480, row: 1, empty: 0, }, { lod: 0, renderScale: 480, empty: 0, row: 2, }, { lod: 0, renderScale: 480, empty: 0, row: 3, }, { lod: 0, renderScale: 1920, empty: 0, row: 4, }, { lod: 0, renderScale: 1920, empty: 0, row: 5, }, ]); }); it('getMultiscaleChunksToDraw multiple chunks 2 lods', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 1, 0, 0, 0, 0, // row 1, lod 0 0, 1, 0, 0, 0, // row 2, lod 0 1, 1, 0, 0, 0, // row 3, lod 0 0, 0, 1, 0, 0, // row 4, lod 0 1, 0, 1, 0, 0, // row 5, lod 0 0, 1, 1, 0, 0, // row 6, lod 0 1, 1, 1, 0, 0, // row 7, lod 0 0, 0, 0, 0, 8, // row 8, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect(getDrawChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 4000, viewportWidth, viewportHeight, () => true)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, subChunkBegin: 0, subChunkEnd: 8, }, ]); expect(getDrawChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight, row => row !== 4)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, subChunkBegin: 0, subChunkEnd: 5, }, { lod: 0, renderScale: 1920, row: 5, subChunkBegin: 0, subChunkEnd: 1, }, { lod: 1, renderScale: 3840, row: 8, subChunkBegin: 6, subChunkEnd: 8, }, ]); }); it('getMultiscaleChunksToDraw multiple chunks 2 lods with missing', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 1, 0, 0, 0, 0, // row 1, lod 0 0, 1, 0, 0, 0, // row 2, lod 0 1, 1, 0, 0, 0, // row 3, lod 0 0, 0, 1, 0, 0, // row 4, lod 0 1, 0, 1, 0, 0, // row 5, lod 0 0, 1, 1, 0, 0, // row 6, lod 0 1, 1, 1, 0, 0, // row 7, lod 0 0, 0, 0, 0, 8, // row 8, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect(getDrawChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight, row => row !== 8)) .toEqual([]); }); it('getMultiscaleChunksToDraw multiple chunks 2 lods with empty', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 1, 0, 0, 0, 0, // row 1, lod 0 0, 1, 0, 0, 0, // row 2, lod 0 1, 1, 0, 0, 0, // row 3, lod 0 0, 0, 1, 0, 0, // row 4, lod 0 1, 0, 1, 0, 0, // row 5, lod 0 0, 1, 1, 0, 0, // row 6, lod 0 1, 1, 1, 0, 0, // row 7, lod 0 0, 0, 0, 0, 0x80000008, // row 8, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect(getDrawChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight, () => true)) .toEqual([ { lod: 0, renderScale: 1920, row: 4, subChunkBegin: 0, subChunkEnd: 1, }, { lod: 0, renderScale: 1920, row: 5, subChunkBegin: 0, subChunkEnd: 1, }, ]); expect(getDrawChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight, row => row !== 4)) .toEqual([ { lod: 0, renderScale: 1920, row: 5, subChunkBegin: 0, subChunkEnd: 1, }, ]); }); it('getDesiredMultiscaleMeshChunks multiple chunks 2 lods with empty', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40), vertexOffsets: new Float32Array(2 * 3), octree: Uint32Array.from([ 0, 0, 0, 0, 0, // row 0, lod 0 1, 0, 0, 0, 0, // row 1, lod 0 0, 1, 0, 0, 0, // row 2, lod 0 1, 1, 0, 0, 0, // row 3, lod 0 0, 0, 1, 0, 0x80000000, // row 4, lod 0 1, 0, 1, 0, 0, // row 5, lod 0 0, 1, 1, 0, 0, // row 6, lod 0 1, 1, 1, 0, 0, // row 7, lod 0 0, 0, 0, 0, 8, // row 8, lod 1 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect( getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 1000, viewportWidth, viewportHeight)) .toEqual([ { lod: 1, renderScale: 3840, row: 8, empty: 0, }, { lod: 0, renderScale: 1920, row: 4, empty: 1, }, { lod: 0, renderScale: 1920, row: 5, empty: 0, }, ]); }); it('getDesiredMultiscaleMeshChunks multiple chunks 4 lods', () => { const manifest: MultiscaleMeshManifest = { chunkShape: vec3.fromValues(10, 20, 30), chunkGridSpatialOrigin: vec3.fromValues(5, 6, -50), clipLowerBound: vec3.fromValues(5, 6, -50), clipUpperBound: vec3.fromValues(100, 200, 10), lodScales: Float32Array.of(20, 40, 80, 160, 0), vertexOffsets: new Float32Array(5 * 3), octree: Uint32Array.from([ 5, 3, 0, 0, 0, // row 0: lod=0 7, 0, 3, 0, 0, // row 1: lod=0 7, 1, 3, 0, 0, // row 2: lod=0 7, 3, 2, 0, 0, // row 3: lod=0 1, 7, 0, 0, 0, // row 4: lod=0 2, 7, 0, 0, 0, // row 5: lod=0 5, 4, 0, 0, 0, // row 6: lod=0 6, 4, 0, 0, 0, // row 7: lod=0 6, 4, 1, 0, 0, // row 8: lod=0 6, 5, 1, 0, 0, // row 9: lod=0 7, 5, 1, 0, 0, // row 10: lod=0 4, 7, 1, 0, 0, // row 11: lod=0 5, 7, 1, 0, 0, // row 12: lod=0 6, 6, 1, 0, 0, // row 13: lod=0 7, 6, 1, 0, 0, // row 14: lod=0 6, 7, 1, 0, 0, // row 15: lod=0 7, 7, 1, 0, 0, // row 16: lod=0 7, 4, 2, 0, 0, // row 17: lod=0 7, 5, 2, 0, 0, // row 18: lod=0 6, 7, 2, 0, 0, // row 19: lod=0 7, 7, 2, 0, 0, // row 20: lod=0 7, 7, 3, 0, 0, // row 21: lod=0 7, 6, 4, 0, 0, // row 22: lod=0 7, 7, 4, 0, 0, // row 23: lod=0 10, 3, 0, 0, 0, // row 24: lod=0 11, 3, 0, 0, 0, // row 25: lod=0 8, 1, 2, 0, 0, // row 26: lod=0 9, 1, 2, 0, 0, // row 27: lod=0 8, 0, 3, 0, 0, // row 28: lod=0 9, 0, 3, 0, 0, // row 29: lod=0 8, 1, 3, 0, 0, // row 30: lod=0 9, 1, 3, 0, 0, // row 31: lod=0 10, 0, 2, 0, 0, // row 32: lod=0 2, 1, 0, 0, 1, // row 33: lod=1 3, 0, 1, 1, 3, // row 34: lod=1 3, 1, 1, 3, 4, // row 35: lod=1 0, 3, 0, 4, 5, // row 36: lod=1 1, 3, 0, 5, 6, // row 37: lod=1 2, 2, 0, 6, 7, // row 38: lod=1 3, 2, 0, 7, 11, // row 39: lod=1 2, 3, 0, 11, 13, // row 40: lod=1 3, 3, 0, 13, 17, // row 41: lod=1 3, 2, 1, 17, 19, // row 42: lod=1 3, 3, 1, 19, 22, // row 43: lod=1 3, 3, 2, 22, 24, // row 44: lod=1 5, 1, 0, 24, 26, // row 45: lod=1 4, 0, 1, 26, 32, // row 46: lod=1 5, 0, 1, 32, 33, // row 47: lod=1 1, 0, 0, 33, 36, // row 48: lod=2 0, 1, 0, 36, 38, // row 49: lod=2 1, 1, 0, 38, 44, // row 50: lod=2 1, 1, 1, 44, 45, // row 51: lod=2 2, 0, 0, 45, 48, // row 52: lod=2 0, 0, 0, 48, 52, // row 53: lod=3 1, 0, 0, 52, 53, // row 54: lod=3 0, 0, 0, 53, 55, // row 55: lod=4 ]), }; const viewportWidth = 640; const viewportHeight = 480; const modelViewProjection = mat4.perspective(mat4.create(), Math.PI / 2, viewportWidth / viewportHeight, 5, 100); expect( getDesiredChunkList( manifest, modelViewProjection, /*detailCutoff=*/ 100000, viewportWidth, viewportHeight)) .toEqual([ { lod: 3, renderScale: 15360, row: 53, empty: 0, }, ]); }); });
the_stack
import uuid = require('uuid/v1'); import {JSDOM, DOMWindow} from '@forbeslindesay/jsdom'; import Browser from './Browser'; import Tab from './Tab'; import WebdriverCookie from './WebdriverCookie'; import WebdriverElementReference from './WebdriverElementReference'; import WebdriverSelectorType from './WebdriverSelectorType'; import WebdriverStatus, {SuccessStatus} from './WebdriverStatus'; import WebdriverTimeoutType from './WebdriverTimeoutType'; import {Cookie, Store} from 'tough-cookie'; import MouseButton from './MouseButton'; import StorageLevel from './StorageLevel'; interface ElementList { readonly length: number; readonly [index: number]: Element; } type WebdriverSuccessResponse<T> = { status: 0, sessionId: string, value: T, } type WebdriverErrorResponse = {status: WebdriverStatus, value: {message: string}}; type WebdriverResponse<T> = WebdriverSuccessResponse<T> | WebdriverErrorResponse; const XPathSelectorError = { status: WebdriverStatus.InvalidSelector, value: {message: 'Taxi Rank does not support XPath selectors.'}, }; function createResponse<T = void>(request: {params: {sessionId: string}}, value: T): WebdriverResponse<T> { return {status: SuccessStatus, sessionId: request.params.sessionId, value}; } function isWebdriverResponse<T>(value: T | WebdriverResponse<T>): value is WebdriverResponse<T> { return value && typeof value === 'object' && typeof (value as any).status === 'number'; } function withCallback<T>(fn: (cb: (err: any, res: T) => any) => void): Promise<T> { return new Promise((resolve, reject) => { fn((err, res) => { if (err) return reject(err); else resolve((res as any)); }) }); } class ElementStore { private readonly elements: Map<string, Element> = new Map(); private readonly elementIDs: Map<Element, string> = new Map(); private _nextIndex = 0; storeElement(tab: Tab, element: Element): WebdriverElementReference { const oldID = this.elementIDs.get(element); if (oldID) { return {ELEMENT: oldID}; } const id = '' + (this._nextIndex++); this.elements.set(id, element); this.elementIDs.set(element, id); return {ELEMENT: id}; } getElement(reference: WebdriverElementReference | string): Element | null { return this.elements.get(typeof reference === 'string' ? reference : reference.ELEMENT) || null; } } class WebdriverSession { public readonly browser: Browser; public readonly elements = new ElementStore(); public timeouts: Map<WebdriverTimeoutType, number> = new Map([ [WebdriverTimeoutType.ASYNC_SCRIPT, 5000], [WebdriverTimeoutType.IMPLICIT, 5000], [WebdriverTimeoutType.PAGE_LOAD, 5000], [WebdriverTimeoutType.SCRIPT, 5000], ]); public mouseLocation: null | {elementID: string, xoffset: number, yoffset: number}; constructor(browser: Browser) { this.browser = browser; } } class Webdriver { private readonly _activeSessions: Map<string, WebdriverSession> = new Map(); async createSession( request: { body: { desiredCapabilities: {[key: string]: string | number | void | null}, requiredCapabilities: {[key: string]: string | number | void | null}, }, }, ): Promise<WebdriverResponse<Object>> { const runScripts = request.body.desiredCapabilities.runScripts || request.body.desiredCapabilities.runScripts || 'dangerously'; if (runScripts !== 'dangerously' && runScripts !== 'outside-only') { return { status: WebdriverStatus.SessionNotCreatedException, value: {message: 'The only valid values for the runScripts capability are "dangerously" and "outside-only"'}, }; } const capabilities = {runScripts: (runScripts as 'dangerously' | 'outside-only')}; const sessionId = uuid(); const currentSession = new WebdriverSession(new Browser({runScripts: capabilities.runScripts})); this._activeSessions.set(sessionId, currentSession); // TODO: initialise lots of things from capabilities here return {status: SuccessStatus, sessionId, value: capabilities}; } async deleteSession(request: {params: {sessionId: string}}): Promise<WebdriverResponse<void>> { const session = this._activeSessions.get(request.params.sessionId); if (session) { session.browser.dispose(); this._activeSessions.delete(request.params.sessionId); } return createResponse(request, undefined); } private async _withSession<T>(request: {params: {sessionId: string}}, fn: (session: WebdriverSession) => Promise<T | WebdriverResponse<T>>): Promise<WebdriverResponse<T>> { const session = this._activeSessions.get(request.params.sessionId); if (!session) { return {status: WebdriverStatus.NoSuchSession, value: {message: `No session with id, ${request.params.sessionId} was found.`}}; } const result = await fn(session); if (isWebdriverResponse(result)) { return result; } else { return createResponse<T>(request, result); } } setTimeouts(request: {body: {type: WebdriverTimeoutType, ms: number}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { session.timeouts.set(request.body.type, request.body.ms); }); } setAsyncScriptTimeOut(request: {body: {ms: number}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { session.timeouts.set(WebdriverTimeoutType.ASYNC_SCRIPT, request.body.ms); }); } getActiveWindowHandle(request: {params: {sessionId: string}}): Promise<WebdriverResponse<string>> { return this._withSession<string>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } return tab.id; }); } setUrl(request: {body: {url: string}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); dom.window.location.href = request.body.url; await tab.whenReady(); }); } goBack(request: {body: {url: string}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); dom.window.history.back(); await tab.whenReady(); }); } goForward(request: {body: {url: string}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); dom.window.history.forward(); await tab.whenReady(); }); } refresh(request: {body: {url: string}, params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); dom.window.location.reload(); await tab.whenReady(); }); } getElementFromResponse(request: {body: {using: WebdriverSelectorType, value: string}, params: {sessionId: string}}, elementsResponse: WebdriverResponse<Array<WebdriverElementReference>>): WebdriverResponse<WebdriverElementReference> { if (elementsResponse.status !== SuccessStatus) { return <WebdriverErrorResponse>elementsResponse; } const elements = (<WebdriverSuccessResponse<Array<WebdriverElementReference>>>elementsResponse).value; if (elements.length) { return createResponse(request, elements[0]); } return {status: WebdriverStatus.NoSuchElement, value: {message: `There do not seem to be any elements with the selector "${request.body.value}"`}}; } async getElement(request: {body: {using: WebdriverSelectorType, value: string}, params: {sessionId: string}}): Promise<WebdriverResponse<WebdriverElementReference>> { return this.getElementFromResponse(request, await this.getElements(request)); } private _htmlCollectionToArray(session: WebdriverSession, tab: Tab, elements: HTMLCollectionOf<Element>): Array<WebdriverElementReference> { const result = []; for (let i = 0; i < elements.length; i++) { result.push(session.elements.storeElement(tab, elements[i])); } return result; } private _getElementsInContext( ctx: { using: WebdriverSelectorType, value: string, parent: Document | Element, session: WebdriverSession, }, ): Array<Element> { function htmlCollectionToArray(elements: ElementList): Array<Element> { const result = []; for (let i = 0; i < elements.length; i++) { result.push(elements[i]); } return result; } switch (ctx.using) { case WebdriverSelectorType.CLASS: return htmlCollectionToArray(ctx.parent.getElementsByClassName(ctx.value)); case WebdriverSelectorType.CSS: return htmlCollectionToArray(ctx.parent.querySelectorAll(ctx.value)); case WebdriverSelectorType.ID: return htmlCollectionToArray( ctx.parent.querySelectorAll('#' + ctx.value) ).filter(element => element.id === ctx.value); case WebdriverSelectorType.NAME: return htmlCollectionToArray( ctx.parent.querySelectorAll(`[name="${ctx.value}"]`) ).filter(element => element.getAttribute('name') === ctx.value); case WebdriverSelectorType.LINK_TEXT: return htmlCollectionToArray( ctx.parent.getElementsByTagName('a') ).filter(element => element.textContent === ctx.value); case WebdriverSelectorType.PARTIAL_LINK_TEXT: return htmlCollectionToArray( ctx.parent.getElementsByTagName('a') ).filter(element => (element.textContent || '').indexOf(ctx.value) !== -1); case WebdriverSelectorType.TAG: return htmlCollectionToArray( ctx.parent.getElementsByTagName(ctx.value) ); case WebdriverSelectorType.XPATH: throw new Error('XPath Selectors are not implemented'); } } getElements(request: {body: {using: WebdriverSelectorType, value: string}, params: {sessionId: string}}): Promise<WebdriverResponse<Array<WebdriverElementReference>>> { return this._withSession<Array<WebdriverElementReference>>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return []; } const dom = await tab.whenReady(); if (request.body.using === WebdriverSelectorType.ID) { const element = dom.window.document.getElementById(request.body.value); return element ? [session.elements.storeElement(tab, element)] : []; } if (request.body.using === WebdriverSelectorType.XPATH) { return XPathSelectorError; } return this._getElementsInContext({ using: request.body.using, value: request.body.value, parent: dom.window.document, session, }).map(element => session.elements.storeElement(tab, element)); }); } async getChildElement(request: {body: {using: WebdriverSelectorType, value: string}, params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<WebdriverElementReference>> { return this.getElementFromResponse(request, await this.getChildElements(request)); } getChildElements(request: {body: {using: WebdriverSelectorType, value: string}, params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<Array<WebdriverElementReference>>> { return this._withElement<Array<WebdriverElementReference>>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return []; } const dom = await tab.whenReady(); if (request.body.using === WebdriverSelectorType.ID) { return {status: WebdriverStatus.UnknownError, value: {message: 'Cannot use an element ID selector on another element, only on body'}}; } if (request.body.using === WebdriverSelectorType.XPATH) { return XPathSelectorError; } return this._getElementsInContext({ using: request.body.using, value: request.body.value, parent: element, session, }).map(element => session.elements.storeElement(tab, element)); }); } compareElements(request: {params: {elementA: string, elementB: string, sessionId: string}}): Promise<WebdriverResponse<boolean>> { return this._withSession<boolean>(request, async (session) => { return request.params.elementA === request.params.elementB; }); } getActiveElement(request: {params: {sessionId: string}}): Promise<WebdriverResponse<WebdriverElementReference>> { return this._withSession<WebdriverElementReference>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return session.elements.storeElement(tab, dom.window.document.activeElement); }); } getSource(request: {params: {sessionId: string}}): Promise<WebdriverResponse<string>> { return this._withSession<string>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return dom.serialize(); }); } getTitle(request: {params: {sessionId: string}}): Promise<WebdriverResponse<string>> { return this._withSession<string>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return dom.window.document.title; }); } getUrl(request: {params: {sessionId: string}}): Promise<WebdriverResponse<string>> { return this._withSession<string>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return dom.window.location.href; }); } deleteAllCookies(request: {params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession(request, async (session) => { const store: Store = (session.browser.cookies as any).store; const cookies = await withCallback<Array<Cookie>>(cb => store.getAllCookies(cb)); for (const cookie of cookies) { await withCallback<void>(cb => store.removeCookie(cookie.domain, cookie.path, cookie.key, err => cb(err, undefined))); } }); } deleteCookie(request: {params: {sessionId: string, key: string}}): Promise<WebdriverResponse<void>> { return this._withSession(request, async (session) => { const store: Store = (session.browser.cookies as any).store; const cookies = await withCallback<Array<Cookie>>(cb => store.getAllCookies(cb)); for (const cookie of cookies) { if (cookie.key === request.params.key) { await withCallback<void>(cb => store.removeCookie(cookie.domain, cookie.path, cookie.key, err => cb(err, undefined))); } } }); } setCookie(request: {params: {sessionId: string}, body: {cookie: WebdriverCookie}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); await new Promise((resolve, reject) => { const c = request.body.cookie; session.browser.cookies.setCookie(new Cookie({ key: c.name, value: c.value, // expires: undefined, maxAge: c.expiry || 'Infinity', domain: c.domain, path: c.path, secure: c.secure || false, httpOnly: c.httpOnly || false, // extensions: [], creation: new Date(), // creationIndex: Date.now(), // hostOnly: false, // pathIsDefault: false, lastAccessed: new Date(), }), dom.window.location.href, (err: any) => { if (err) reject(err); else resolve(); }); }); }); } getCookies(request: {params: {sessionId: string}}): Promise<WebdriverResponse<Array<WebdriverCookie>>> { return this._withSession<Array<WebdriverCookie>>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); const cookies = await new Promise<Cookie[]>((resolve, reject) => { session.browser.cookies.getCookies(dom.window.location.href, (err, cookies) => { if (err) reject(err); else resolve(cookies); }); }); return cookies.map((c): WebdriverCookie => ({ name: c.key, value: c.value, path: c.path, domain: c.domain, httpOnly: c.httpOnly, secure: c.secure, expiry: typeof c.maxAge === 'number' ? c.maxAge : undefined, })); }); } private async _withElement<T>(request: {params: {sessionId: string, elementId: string}}, fn: (session: WebdriverSession, element: Element) => Promise<T | WebdriverResponse<T>>): Promise<WebdriverResponse<T>> { const session = this._activeSessions.get(request.params.sessionId); if (!session) { return {status: WebdriverStatus.NoSuchSession, value: {message: `No session with id, ${request.params.sessionId} was found.`}}; } const element = session.elements.getElement(request.params.elementId); if (!element) { return {status: WebdriverStatus.NoSuchElement, value: {message: `No element with id, ${request.params.elementId} was found.`}}; } const result = await fn(session, element); if (isWebdriverResponse(result)) { return result; } else { return createResponse<T>(request, result); } } getTagName(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<string>> { return this._withElement(request, async (session, element) => { return element.tagName.toLowerCase(); }); } getAttribute(request: {params: {sessionId: string, elementId: string, attributeName: string}}): Promise<WebdriverResponse<string | null>> { return this._withElement<string | null>(request, async (session, element) => { if (request.params.attributeName === 'value' && isInputlike(element)) { return element.value; } if (request.params.attributeName === 'checked' && isInput(element)) { // TODO: I'm not sure this is quite right return element.checked ? 'checked' : null; } return element.getAttribute(request.params.attributeName); }); } getCssProperty(request: {params: {sessionId: string, elementId: string, propertyName: string}}): Promise<WebdriverResponse<string | null>> { return this._withElement<string | null>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return dom.window.getComputedStyle(element)[(request.params.propertyName as any)] || null; }); } getEnabled(request: {params: {sessionId: string, elementId: string, attributeName: string}}): Promise<WebdriverResponse<boolean>> { return this._withElement<boolean>(request, async (session, element) => { return !(element as any).disabled; }); } getSelected(request: {params: {sessionId: string, elementId: string, attributeName: string}}): Promise<WebdriverResponse<boolean>> { return this._withElement<boolean>(request, async (session, element) => { return !!(element as any).checked; }); } getText(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<string>> { return this._withElement<string>(request, async (session, element) => { return element.textContent || ''; }); } click(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<void>> { return this._withElement<void>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); // element.click does not fire mousedown and mouseup so we manually create all three events const style = dom.window.getComputedStyle(element); const top = style.top ? parseInt(style.top, 10) : 0; const left = style.left ? parseInt(style.left, 10) : 0; const x = style.width ? parseInt(style.width, 10) / 2 : 0; const y = style.height ? parseInt(style.height, 10) / 2 : 0; ['mousedown', 'click', 'mouseup'].forEach(name => { const e = dom.window.document.createEvent('MouseEvent'); e.initMouseEvent(name, true, true, dom.window, 0, left + x, top + y, left + x, top + y, false, false, false, false, MouseButton.LEFT, null); element.dispatchEvent(e); }); }); } moveTo(request: {params: {sessionId: string}, body: {element?: string, xoffset?: number, yoffset?: number}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { if (!request.body.element) { return { status: WebdriverStatus.UnknownError, value: {message: 'Taxi Rank does not support moving the mouse to arbitrary locations, you must specify an element.'}, }; } session.mouseLocation = { elementID: request.body.element, xoffset: request.body.xoffset || 0, yoffset: request.body.yoffset || 0, }; }); } globalClick(request: {params: {sessionId: string}, body: {button: MouseButton}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { if (!session.mouseLocation) { return { status: WebdriverStatus.UnknownError, value: {message: 'Taxi Rank requires you to move the mouse before you can click it.'}, }; } const element = session.elements.getElement(session.mouseLocation.elementID); if (!element) { return { status: WebdriverStatus.UnknownError, value: {message: 'Could not find an element with ID ' + session.mouseLocation.elementID + '.'}, }; } const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); // element.click does not fire mousedown and mouseup so we manually create all three events const style = dom.window.getComputedStyle(element); const top = style.top ? parseInt(style.top, 10) : 0; const left = style.left ? parseInt(style.left, 10) : 0; const x = session.mouseLocation.xoffset; const y = session.mouseLocation.yoffset; ['mousedown', 'click', 'mouseup'].forEach(name => { const e = dom.window.document.createEvent('MouseEvent'); e.initMouseEvent(name, true, true, dom.window, 0, left + x, top + y, left + x, top + y, false, false, false, false, request.body.button, null); element.dispatchEvent(e); }); }); } submit(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<void>> { return this._withElement<void>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); if (!isForm(element)) { return {status: WebdriverStatus.UnknownError, value: {message: 'This element is not a form, it cannot be submitted.'}}; } const form: HTMLFormElement = element; const submit = dom.window.document.createEvent('HTMLEvents'); submit.initEvent('submit', true, true); if (form.dispatchEvent(submit)) { form.submit(); } await tab.whenReady(); }); } sendKeys(request: {params: {sessionId: string}, body: {value: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); for (const key of request.body.value) { // key is a single character const options = { key: key.toLowerCase(), char: key, charCode: key.charCodeAt(0), shiftKey: key !== key.toLowerCase(), keyCode: key.toUpperCase().charCodeAt(0), }; const KeyboardEvent = (dom.window as any).KeyboardEvent; dom.window.document.activeElement.dispatchEvent(new KeyboardEvent('keydown', options)); dom.window.document.activeElement.dispatchEvent(new KeyboardEvent('keypress', options)); dom.window.document.activeElement.dispatchEvent(new KeyboardEvent('keyup', options)); } }); } execute(request: {params: {sessionId: string}, body: {script: string, args: Array<string>}}): Promise<WebdriverResponse<any>> { return this._withSession(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return (dom.window as any).Function('', request.body.script)(...request.body.args); }); } executeAsync(request: {params: {sessionId: string}, body: {script: string, args: Array<string>}}): Promise<WebdriverResponse<any>> { return this.execute(request); } _getStorage(window: DOMWindow, level: StorageLevel): Storage { switch (level) { case StorageLevel.Local: return window.localStorage; case StorageLevel.Session: return window.sessionStorage; } } setStorageItem(request: {params: {sessionId: string, storageLevel: StorageLevel}, body: {key: string, value: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); this._getStorage(dom.window, request.params.storageLevel).setItem(request.body.key, request.body.value); }); } getStorageItem(request: {params: {sessionId: string, storageLevel: StorageLevel, key: string}}): Promise<WebdriverResponse<string | null>> { return this._withSession<string | null>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return this._getStorage(dom.window, request.params.storageLevel).getItem(request.params.key); }); } getStorageKeys(request: {params: {sessionId: string, storageLevel: StorageLevel}}): Promise<WebdriverResponse<Array<string>>> { return this._withSession<Array<string>>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); const storage = this._getStorage(dom.window, request.params.storageLevel); const keys = []; for (let i = 0; i < storage.length; i++) { const key = storage.key(i); if (typeof key === 'string') { keys.push(key); } } return keys; }); } getStorageSize(request: {params: {sessionId: string, storageLevel: StorageLevel}}): Promise<WebdriverResponse<number>> { return this._withSession<number>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); return this._getStorage(dom.window, request.params.storageLevel).length; }); } clearStorage(request: {params: {sessionId: string, storageLevel: StorageLevel}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); this._getStorage(dom.window, request.params.storageLevel).clear(); }); } removeStorageItem(request: {params: {sessionId: string, storageLevel: StorageLevel, key: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); this._getStorage(dom.window, request.params.storageLevel).removeItem(request.params.key); }); } _setValue(window: DOMWindow, element: Element, value: string): null | WebdriverErrorResponse { if (!isInputlike(element)) { return {status: WebdriverStatus.InvalidElementState, value: {message: 'You cannot set a value for an element with the tag name ' + element.tagName}}; } if (element.disabled || element.readOnly) { return {status: WebdriverStatus.InvalidElementState, value: {message: 'You cannot set a value for an element that is disabled or read only'}}; } // Switch focus to field, change value and emit the input event (HTML5) element.focus(); // `field.value = value` does not work if there is a custom property descriptor, e.g. in React // TODO: check what the actual spec compliant way of doing this is const descriptor = Object.getOwnPropertyDescriptor(element.constructor.prototype, 'value'); if (!descriptor.set) { throw new Error('Corrupted element prototype'); } descriptor.set.call(element, value); const e = window.document.createEvent('HTMLEvents'); e.initEvent('input', true, true); element.dispatchEvent(e); // Switch focus out of field, if value changed, this will emit change event element.blur(); return null; } clear(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<void>> { return this._withElement<void>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); this._setValue(dom.window, element, ''); }); } appendValue(request: {params: {sessionId: string, elementId: string}, body: {value: Array<string>}}): Promise<WebdriverResponse<void>> { return this._withElement<void>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); if (!isInputlike(element)) { return {status: WebdriverStatus.InvalidElementState, value: {message: 'You cannot set a value for an element with the tag name ' + element.tagName}}; } this._setValue(dom.window, element, element.value + request.body.value.join('')); }); } getDisplayed(request: {params: {sessionId: string, elementId: string}}): Promise<WebdriverResponse<boolean>> { return this._withElement<boolean>(request, async (session, element) => { const tab = session.browser.currentTab; if (!tab) { return {status: WebdriverStatus.UnknownError, value: {message: 'No tab currently open'}}; } const dom = await tab.whenReady(); const display = dom.window.getComputedStyle(element).display; return display !== 'none'; }); } closeActiveWindow(request: {params: {sessionId: string}}): Promise<WebdriverResponse<void>> { return this._withSession<void>(request, async (session) => { const tab = session.browser.currentTab; if (tab) { tab.close(); } }); } } function isInput(element: Element): element is HTMLInputElement { return element.tagName === 'INPUT'; } function isInputlike(element: Element): element is HTMLTextAreaElement | HTMLInputElement { return element.tagName === 'TEXTAREA' || element.tagName === 'INPUT'; } function isForm(element: Element): element is HTMLFormElement { return element.tagName === 'FORM'; } export default Webdriver;
the_stack
import inspect from '../jsutils/inspect.js'; import devAssert from '../jsutils/devAssert.js'; import { syntaxError } from '../error/syntaxError.js'; import { Kind } from './kinds.js'; import { Source } from './source.js'; import { DirectiveLocation } from './directiveLocation.js'; import { TokenKind } from './tokenKind.js'; import { Lexer, isPunctuatorTokenKind } from './lexer.js'; import { Location } from './ast.js'; /** * Configuration options to control parser behavior */ /** * Given a GraphQL source, parses it into a Document. * Throws GraphQLError if a syntax error is encountered. */ export function parse(source, options) { const parser = new Parser(source, options); return parser.parseDocument(); } /** * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for * that value. * Throws GraphQLError if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Values directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: valueFromAST(). */ export function parseValue(source, options) { const parser = new Parser(source, options); parser.expectToken(TokenKind.SOF); const value = parser.parseValueLiteral(false); parser.expectToken(TokenKind.EOF); return value; } /** * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for * that type. * Throws GraphQLError if a syntax error is encountered. * * This is useful within tools that operate upon GraphQL Types directly and * in isolation of complete GraphQL documents. * * Consider providing the results to the utility function: typeFromAST(). */ export function parseType(source, options) { const parser = new Parser(source, options); parser.expectToken(TokenKind.SOF); const type = parser.parseTypeReference(); parser.expectToken(TokenKind.EOF); return type; } class Parser { constructor(source, options) { const sourceObj = typeof source === 'string' ? new Source(source) : source; devAssert(sourceObj instanceof Source, `Must provide Source. Received: ${inspect(sourceObj)}.`); this._lexer = new Lexer(sourceObj); this._options = options; } /** * Converts a name lex token into a name parse node. */ parseName() { const token = this.expectToken(TokenKind.NAME); return { kind: Kind.NAME, value: token.value, loc: this.loc(token) }; } // Implements the parsing rules in the Document section. /** * Document : Definition+ */ parseDocument() { const start = this._lexer.token; return { kind: Kind.DOCUMENT, definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF), loc: this.loc(start) }; } /** * Definition : * - ExecutableDefinition * - TypeSystemDefinition * - TypeSystemExtension * * ExecutableDefinition : * - OperationDefinition * - FragmentDefinition */ parseDefinition() { if (this.peek(TokenKind.NAME)) { switch (this._lexer.token.value) { case 'query': case 'mutation': case 'subscription': return this.parseOperationDefinition(); case 'fragment': return this.parseFragmentDefinition(); case 'schema': case 'scalar': case 'type': case 'interface': case 'union': case 'enum': case 'input': case 'directive': return this.parseTypeSystemDefinition(); case 'extend': return this.parseTypeSystemExtension(); } } else if (this.peek(TokenKind.BRACE_L)) { return this.parseOperationDefinition(); } else if (this.peekDescription()) { return this.parseTypeSystemDefinition(); } throw this.unexpected(); } // Implements the parsing rules in the Operations section. /** * OperationDefinition : * - SelectionSet * - OperationType Name? VariableDefinitions? Directives? SelectionSet */ parseOperationDefinition() { const start = this._lexer.token; if (this.peek(TokenKind.BRACE_L)) { return { kind: Kind.OPERATION_DEFINITION, operation: 'query', name: undefined, variableDefinitions: [], directives: [], selectionSet: this.parseSelectionSet(), loc: this.loc(start) }; } const operation = this.parseOperationType(); let name; if (this.peek(TokenKind.NAME)) { name = this.parseName(); } return { kind: Kind.OPERATION_DEFINITION, operation, name, variableDefinitions: this.parseVariableDefinitions(), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), loc: this.loc(start) }; } /** * OperationType : one of query mutation subscription */ parseOperationType() { const operationToken = this.expectToken(TokenKind.NAME); switch (operationToken.value) { case 'query': return 'query'; case 'mutation': return 'mutation'; case 'subscription': return 'subscription'; } throw this.unexpected(operationToken); } /** * VariableDefinitions : ( VariableDefinition+ ) */ parseVariableDefinitions() { return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R); } /** * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? */ parseVariableDefinition() { const start = this._lexer.token; return { kind: Kind.VARIABLE_DEFINITION, variable: this.parseVariable(), type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()), defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined, directives: this.parseDirectives(true), loc: this.loc(start) }; } /** * Variable : $ Name */ parseVariable() { const start = this._lexer.token; this.expectToken(TokenKind.DOLLAR); return { kind: Kind.VARIABLE, name: this.parseName(), loc: this.loc(start) }; } /** * SelectionSet : { Selection+ } */ parseSelectionSet() { const start = this._lexer.token; return { kind: Kind.SELECTION_SET, selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R), loc: this.loc(start) }; } /** * Selection : * - Field * - FragmentSpread * - InlineFragment */ parseSelection() { return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); } /** * Field : Alias? Name Arguments? Directives? SelectionSet? * * Alias : Name : */ parseField() { const start = this._lexer.token; const nameOrAlias = this.parseName(); let alias; let name; if (this.expectOptionalToken(TokenKind.COLON)) { alias = nameOrAlias; name = this.parseName(); } else { name = nameOrAlias; } return { kind: Kind.FIELD, alias, name, arguments: this.parseArguments(false), directives: this.parseDirectives(false), selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined, loc: this.loc(start) }; } /** * Arguments[Const] : ( Argument[?Const]+ ) */ parseArguments(isConst) { const item = isConst ? this.parseConstArgument : this.parseArgument; return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R); } /** * Argument[Const] : Name : Value[?Const] */ parseArgument() { const start = this._lexer.token; const name = this.parseName(); this.expectToken(TokenKind.COLON); return { kind: Kind.ARGUMENT, name, value: this.parseValueLiteral(false), loc: this.loc(start) }; } parseConstArgument() { const start = this._lexer.token; return { kind: Kind.ARGUMENT, name: this.parseName(), value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)), loc: this.loc(start) }; } // Implements the parsing rules in the Fragments section. /** * Corresponds to both FragmentSpread and InlineFragment in the spec. * * FragmentSpread : ... FragmentName Directives? * * InlineFragment : ... TypeCondition? Directives? SelectionSet */ parseFragment() { const start = this._lexer.token; this.expectToken(TokenKind.SPREAD); const hasTypeCondition = this.expectOptionalKeyword('on'); if (!hasTypeCondition && this.peek(TokenKind.NAME)) { return { kind: Kind.FRAGMENT_SPREAD, name: this.parseFragmentName(), directives: this.parseDirectives(false), loc: this.loc(start) }; } return { kind: Kind.INLINE_FRAGMENT, typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), loc: this.loc(start) }; } /** * FragmentDefinition : * - fragment FragmentName on TypeCondition Directives? SelectionSet * * TypeCondition : NamedType */ parseFragmentDefinition() { const start = this._lexer.token; this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes // the grammar of FragmentDefinition: // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet if (this._options?.experimentalFragmentVariables === true) { return { kind: Kind.FRAGMENT_DEFINITION, name: this.parseFragmentName(), variableDefinitions: this.parseVariableDefinitions(), typeCondition: (this.expectKeyword('on'), this.parseNamedType()), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), loc: this.loc(start) }; } return { kind: Kind.FRAGMENT_DEFINITION, name: this.parseFragmentName(), typeCondition: (this.expectKeyword('on'), this.parseNamedType()), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), loc: this.loc(start) }; } /** * FragmentName : Name but not `on` */ parseFragmentName() { if (this._lexer.token.value === 'on') { throw this.unexpected(); } return this.parseName(); } // Implements the parsing rules in the Values section. /** * Value[Const] : * - [~Const] Variable * - IntValue * - FloatValue * - StringValue * - BooleanValue * - NullValue * - EnumValue * - ListValue[?Const] * - ObjectValue[?Const] * * BooleanValue : one of `true` `false` * * NullValue : `null` * * EnumValue : Name but not `true`, `false` or `null` */ parseValueLiteral(isConst) { const token = this._lexer.token; switch (token.kind) { case TokenKind.BRACKET_L: return this.parseList(isConst); case TokenKind.BRACE_L: return this.parseObject(isConst); case TokenKind.INT: this._lexer.advance(); return { kind: Kind.INT, value: token.value, loc: this.loc(token) }; case TokenKind.FLOAT: this._lexer.advance(); return { kind: Kind.FLOAT, value: token.value, loc: this.loc(token) }; case TokenKind.STRING: case TokenKind.BLOCK_STRING: return this.parseStringLiteral(); case TokenKind.NAME: this._lexer.advance(); switch (token.value) { case 'true': return { kind: Kind.BOOLEAN, value: true, loc: this.loc(token) }; case 'false': return { kind: Kind.BOOLEAN, value: false, loc: this.loc(token) }; case 'null': return { kind: Kind.NULL, loc: this.loc(token) }; default: return { kind: Kind.ENUM, value: token.value, loc: this.loc(token) }; } case TokenKind.DOLLAR: if (!isConst) { return this.parseVariable(); } break; } throw this.unexpected(); } parseStringLiteral() { const token = this._lexer.token; this._lexer.advance(); return { kind: Kind.STRING, value: token.value, block: token.kind === TokenKind.BLOCK_STRING, loc: this.loc(token) }; } /** * ListValue[Const] : * - [ ] * - [ Value[?Const]+ ] */ parseList(isConst) { const start = this._lexer.token; const item = () => this.parseValueLiteral(isConst); return { kind: Kind.LIST, values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), loc: this.loc(start) }; } /** * ObjectValue[Const] : * - { } * - { ObjectField[?Const]+ } */ parseObject(isConst) { const start = this._lexer.token; const item = () => this.parseObjectField(isConst); return { kind: Kind.OBJECT, fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), loc: this.loc(start) }; } /** * ObjectField[Const] : Name : Value[?Const] */ parseObjectField(isConst) { const start = this._lexer.token; const name = this.parseName(); this.expectToken(TokenKind.COLON); return { kind: Kind.OBJECT_FIELD, name, value: this.parseValueLiteral(isConst), loc: this.loc(start) }; } // Implements the parsing rules in the Directives section. /** * Directives[Const] : Directive[?Const]+ */ parseDirectives(isConst) { const directives = []; while (this.peek(TokenKind.AT)) { directives.push(this.parseDirective(isConst)); } return directives; } /** * Directive[Const] : @ Name Arguments[?Const]? */ parseDirective(isConst) { const start = this._lexer.token; this.expectToken(TokenKind.AT); return { kind: Kind.DIRECTIVE, name: this.parseName(), arguments: this.parseArguments(isConst), loc: this.loc(start) }; } // Implements the parsing rules in the Types section. /** * Type : * - NamedType * - ListType * - NonNullType */ parseTypeReference() { const start = this._lexer.token; let type; if (this.expectOptionalToken(TokenKind.BRACKET_L)) { type = this.parseTypeReference(); this.expectToken(TokenKind.BRACKET_R); type = { kind: Kind.LIST_TYPE, type, loc: this.loc(start) }; } else { type = this.parseNamedType(); } if (this.expectOptionalToken(TokenKind.BANG)) { return { kind: Kind.NON_NULL_TYPE, type, loc: this.loc(start) }; } return type; } /** * NamedType : Name */ parseNamedType() { const start = this._lexer.token; return { kind: Kind.NAMED_TYPE, name: this.parseName(), loc: this.loc(start) }; } // Implements the parsing rules in the Type Definition section. /** * TypeSystemDefinition : * - SchemaDefinition * - TypeDefinition * - DirectiveDefinition * * TypeDefinition : * - ScalarTypeDefinition * - ObjectTypeDefinition * - InterfaceTypeDefinition * - UnionTypeDefinition * - EnumTypeDefinition * - InputObjectTypeDefinition */ parseTypeSystemDefinition() { // Many definitions begin with a description and require a lookahead. const keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token; if (keywordToken.kind === TokenKind.NAME) { switch (keywordToken.value) { case 'schema': return this.parseSchemaDefinition(); case 'scalar': return this.parseScalarTypeDefinition(); case 'type': return this.parseObjectTypeDefinition(); case 'interface': return this.parseInterfaceTypeDefinition(); case 'union': return this.parseUnionTypeDefinition(); case 'enum': return this.parseEnumTypeDefinition(); case 'input': return this.parseInputObjectTypeDefinition(); case 'directive': return this.parseDirectiveDefinition(); } } throw this.unexpected(keywordToken); } peekDescription() { return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING); } /** * Description : StringValue */ parseDescription() { if (this.peekDescription()) { return this.parseStringLiteral(); } } /** * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } */ parseSchemaDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('schema'); const directives = this.parseDirectives(true); const operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R); return { kind: Kind.SCHEMA_DEFINITION, description, directives, operationTypes, loc: this.loc(start) }; } /** * OperationTypeDefinition : OperationType : NamedType */ parseOperationTypeDefinition() { const start = this._lexer.token; const operation = this.parseOperationType(); this.expectToken(TokenKind.COLON); const type = this.parseNamedType(); return { kind: Kind.OPERATION_TYPE_DEFINITION, operation, type, loc: this.loc(start) }; } /** * ScalarTypeDefinition : Description? scalar Name Directives[Const]? */ parseScalarTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('scalar'); const name = this.parseName(); const directives = this.parseDirectives(true); return { kind: Kind.SCALAR_TYPE_DEFINITION, description, name, directives, loc: this.loc(start) }; } /** * ObjectTypeDefinition : * Description? * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? */ parseObjectTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('type'); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseDirectives(true); const fields = this.parseFieldsDefinition(); return { kind: Kind.OBJECT_TYPE_DEFINITION, description, name, interfaces, directives, fields, loc: this.loc(start) }; } /** * ImplementsInterfaces : * - implements `&`? NamedType * - ImplementsInterfaces & NamedType */ parseImplementsInterfaces() { const types = []; if (this.expectOptionalKeyword('implements')) { // Optional leading ampersand this.expectOptionalToken(TokenKind.AMP); do { types.push(this.parseNamedType()); } while (this.expectOptionalToken(TokenKind.AMP) || // Legacy support for the SDL? this._options?.allowLegacySDLImplementsInterfaces === true && this.peek(TokenKind.NAME)); } return types; } /** * FieldsDefinition : { FieldDefinition+ } */ parseFieldsDefinition() { // Legacy support for the SDL? if (this._options?.allowLegacySDLEmptyFields === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) { this._lexer.advance(); this._lexer.advance(); return []; } return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R); } /** * FieldDefinition : * - Description? Name ArgumentsDefinition? : Type Directives[Const]? */ parseFieldDefinition() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseName(); const args = this.parseArgumentDefs(); this.expectToken(TokenKind.COLON); const type = this.parseTypeReference(); const directives = this.parseDirectives(true); return { kind: Kind.FIELD_DEFINITION, description, name, arguments: args, type, directives, loc: this.loc(start) }; } /** * ArgumentsDefinition : ( InputValueDefinition+ ) */ parseArgumentDefs() { return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R); } /** * InputValueDefinition : * - Description? Name : Type DefaultValue? Directives[Const]? */ parseInputValueDef() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseName(); this.expectToken(TokenKind.COLON); const type = this.parseTypeReference(); let defaultValue; if (this.expectOptionalToken(TokenKind.EQUALS)) { defaultValue = this.parseValueLiteral(true); } const directives = this.parseDirectives(true); return { kind: Kind.INPUT_VALUE_DEFINITION, description, name, type, defaultValue, directives, loc: this.loc(start) }; } /** * InterfaceTypeDefinition : * - Description? interface Name Directives[Const]? FieldsDefinition? */ parseInterfaceTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('interface'); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseDirectives(true); const fields = this.parseFieldsDefinition(); return { kind: Kind.INTERFACE_TYPE_DEFINITION, description, name, interfaces, directives, fields, loc: this.loc(start) }; } /** * UnionTypeDefinition : * - Description? union Name Directives[Const]? UnionMemberTypes? */ parseUnionTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('union'); const name = this.parseName(); const directives = this.parseDirectives(true); const types = this.parseUnionMemberTypes(); return { kind: Kind.UNION_TYPE_DEFINITION, description, name, directives, types, loc: this.loc(start) }; } /** * UnionMemberTypes : * - = `|`? NamedType * - UnionMemberTypes | NamedType */ parseUnionMemberTypes() { const types = []; if (this.expectOptionalToken(TokenKind.EQUALS)) { // Optional leading pipe this.expectOptionalToken(TokenKind.PIPE); do { types.push(this.parseNamedType()); } while (this.expectOptionalToken(TokenKind.PIPE)); } return types; } /** * EnumTypeDefinition : * - Description? enum Name Directives[Const]? EnumValuesDefinition? */ parseEnumTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('enum'); const name = this.parseName(); const directives = this.parseDirectives(true); const values = this.parseEnumValuesDefinition(); return { kind: Kind.ENUM_TYPE_DEFINITION, description, name, directives, values, loc: this.loc(start) }; } /** * EnumValuesDefinition : { EnumValueDefinition+ } */ parseEnumValuesDefinition() { return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R); } /** * EnumValueDefinition : Description? EnumValue Directives[Const]? * * EnumValue : Name */ parseEnumValueDefinition() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseName(); const directives = this.parseDirectives(true); return { kind: Kind.ENUM_VALUE_DEFINITION, description, name, directives, loc: this.loc(start) }; } /** * InputObjectTypeDefinition : * - Description? input Name Directives[Const]? InputFieldsDefinition? */ parseInputObjectTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('input'); const name = this.parseName(); const directives = this.parseDirectives(true); const fields = this.parseInputFieldsDefinition(); return { kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, description, name, directives, fields, loc: this.loc(start) }; } /** * InputFieldsDefinition : { InputValueDefinition+ } */ parseInputFieldsDefinition() { return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R); } /** * TypeSystemExtension : * - SchemaExtension * - TypeExtension * * TypeExtension : * - ScalarTypeExtension * - ObjectTypeExtension * - InterfaceTypeExtension * - UnionTypeExtension * - EnumTypeExtension * - InputObjectTypeDefinition */ parseTypeSystemExtension() { const keywordToken = this._lexer.lookahead(); if (keywordToken.kind === TokenKind.NAME) { switch (keywordToken.value) { case 'schema': return this.parseSchemaExtension(); case 'scalar': return this.parseScalarTypeExtension(); case 'type': return this.parseObjectTypeExtension(); case 'interface': return this.parseInterfaceTypeExtension(); case 'union': return this.parseUnionTypeExtension(); case 'enum': return this.parseEnumTypeExtension(); case 'input': return this.parseInputObjectTypeExtension(); } } throw this.unexpected(keywordToken); } /** * SchemaExtension : * - extend schema Directives[Const]? { OperationTypeDefinition+ } * - extend schema Directives[Const] */ parseSchemaExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('schema'); const directives = this.parseDirectives(true); const operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R); if (directives.length === 0 && operationTypes.length === 0) { throw this.unexpected(); } return { kind: Kind.SCHEMA_EXTENSION, directives, operationTypes, loc: this.loc(start) }; } /** * ScalarTypeExtension : * - extend scalar Name Directives[Const] */ parseScalarTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('scalar'); const name = this.parseName(); const directives = this.parseDirectives(true); if (directives.length === 0) { throw this.unexpected(); } return { kind: Kind.SCALAR_TYPE_EXTENSION, name, directives, loc: this.loc(start) }; } /** * ObjectTypeExtension : * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition * - extend type Name ImplementsInterfaces? Directives[Const] * - extend type Name ImplementsInterfaces */ parseObjectTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('type'); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseDirectives(true); const fields = this.parseFieldsDefinition(); if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { throw this.unexpected(); } return { kind: Kind.OBJECT_TYPE_EXTENSION, name, interfaces, directives, fields, loc: this.loc(start) }; } /** * InterfaceTypeExtension : * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition * - extend interface Name ImplementsInterfaces? Directives[Const] * - extend interface Name ImplementsInterfaces */ parseInterfaceTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('interface'); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseDirectives(true); const fields = this.parseFieldsDefinition(); if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { throw this.unexpected(); } return { kind: Kind.INTERFACE_TYPE_EXTENSION, name, interfaces, directives, fields, loc: this.loc(start) }; } /** * UnionTypeExtension : * - extend union Name Directives[Const]? UnionMemberTypes * - extend union Name Directives[Const] */ parseUnionTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('union'); const name = this.parseName(); const directives = this.parseDirectives(true); const types = this.parseUnionMemberTypes(); if (directives.length === 0 && types.length === 0) { throw this.unexpected(); } return { kind: Kind.UNION_TYPE_EXTENSION, name, directives, types, loc: this.loc(start) }; } /** * EnumTypeExtension : * - extend enum Name Directives[Const]? EnumValuesDefinition * - extend enum Name Directives[Const] */ parseEnumTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('enum'); const name = this.parseName(); const directives = this.parseDirectives(true); const values = this.parseEnumValuesDefinition(); if (directives.length === 0 && values.length === 0) { throw this.unexpected(); } return { kind: Kind.ENUM_TYPE_EXTENSION, name, directives, values, loc: this.loc(start) }; } /** * InputObjectTypeExtension : * - extend input Name Directives[Const]? InputFieldsDefinition * - extend input Name Directives[Const] */ parseInputObjectTypeExtension() { const start = this._lexer.token; this.expectKeyword('extend'); this.expectKeyword('input'); const name = this.parseName(); const directives = this.parseDirectives(true); const fields = this.parseInputFieldsDefinition(); if (directives.length === 0 && fields.length === 0) { throw this.unexpected(); } return { kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, name, directives, fields, loc: this.loc(start) }; } /** * DirectiveDefinition : * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations */ parseDirectiveDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword('directive'); this.expectToken(TokenKind.AT); const name = this.parseName(); const args = this.parseArgumentDefs(); const repeatable = this.expectOptionalKeyword('repeatable'); this.expectKeyword('on'); const locations = this.parseDirectiveLocations(); return { kind: Kind.DIRECTIVE_DEFINITION, description, name, arguments: args, repeatable, locations, loc: this.loc(start) }; } /** * DirectiveLocations : * - `|`? DirectiveLocation * - DirectiveLocations | DirectiveLocation */ parseDirectiveLocations() { // Optional leading pipe this.expectOptionalToken(TokenKind.PIPE); const locations = []; do { locations.push(this.parseDirectiveLocation()); } while (this.expectOptionalToken(TokenKind.PIPE)); return locations; } /* * DirectiveLocation : * - ExecutableDirectiveLocation * - TypeSystemDirectiveLocation * * ExecutableDirectiveLocation : one of * `QUERY` * `MUTATION` * `SUBSCRIPTION` * `FIELD` * `FRAGMENT_DEFINITION` * `FRAGMENT_SPREAD` * `INLINE_FRAGMENT` * * TypeSystemDirectiveLocation : one of * `SCHEMA` * `SCALAR` * `OBJECT` * `FIELD_DEFINITION` * `ARGUMENT_DEFINITION` * `INTERFACE` * `UNION` * `ENUM` * `ENUM_VALUE` * `INPUT_OBJECT` * `INPUT_FIELD_DEFINITION` */ parseDirectiveLocation() { const start = this._lexer.token; const name = this.parseName(); if (DirectiveLocation[name.value] !== undefined) { return name; } throw this.unexpected(start); } // Core parsing utility functions /** * Returns a location object, used to identify the place in * the source that created a given parsed object. */ loc(startToken) { if (this._options?.noLocation !== true) { return new Location(startToken, this._lexer.lastToken, this._lexer.source); } } /** * Determines if the next token is of a given kind */ peek(kind) { return this._lexer.token.kind === kind; } /** * If the next token is of the given kind, return that token after advancing * the lexer. Otherwise, do not change the parser state and throw an error. */ expectToken(kind) { const token = this._lexer.token; if (token.kind === kind) { this._lexer.advance(); return token; } throw syntaxError(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`); } /** * If the next token is of the given kind, return that token after advancing * the lexer. Otherwise, do not change the parser state and return undefined. */ expectOptionalToken(kind) { const token = this._lexer.token; if (token.kind === kind) { this._lexer.advance(); return token; } return undefined; } /** * If the next token is a given keyword, advance the lexer. * Otherwise, do not change the parser state and throw an error. */ expectKeyword(value) { const token = this._lexer.token; if (token.kind === TokenKind.NAME && token.value === value) { this._lexer.advance(); } else { throw syntaxError(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); } } /** * If the next token is a given keyword, return "true" after advancing * the lexer. Otherwise, do not change the parser state and return "false". */ expectOptionalKeyword(value) { const token = this._lexer.token; if (token.kind === TokenKind.NAME && token.value === value) { this._lexer.advance(); return true; } return false; } /** * Helper function for creating an error when an unexpected lexed token * is encountered. */ unexpected(atToken) { const token = atToken ?? this._lexer.token; return syntaxError(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); } /** * Returns a possibly empty list of parse nodes, determined by * the parseFn. This list begins with a lex token of openKind * and ends with a lex token of closeKind. Advances the parser * to the next lex token after the closing token. */ any(openKind, parseFn, closeKind) { this.expectToken(openKind); const nodes = []; while (!this.expectOptionalToken(closeKind)) { nodes.push(parseFn.call(this)); } return nodes; } /** * Returns a list of parse nodes, determined by the parseFn. * It can be empty only if open token is missing otherwise it will always * return non-empty list that begins with a lex token of openKind and ends * with a lex token of closeKind. Advances the parser to the next lex token * after the closing token. */ optionalMany(openKind, parseFn, closeKind) { if (this.expectOptionalToken(openKind)) { const nodes = []; do { nodes.push(parseFn.call(this)); } while (!this.expectOptionalToken(closeKind)); return nodes; } return []; } /** * Returns a non-empty list of parse nodes, determined by * the parseFn. This list begins with a lex token of openKind * and ends with a lex token of closeKind. Advances the parser * to the next lex token after the closing token. */ many(openKind, parseFn, closeKind) { this.expectToken(openKind); const nodes = []; do { nodes.push(parseFn.call(this)); } while (!this.expectOptionalToken(closeKind)); return nodes; } } /** * A helper function to describe a token as a string for debugging */ function getTokenDesc(token) { const value = token.value; return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); } /** * A helper function to describe a token kind as a string for debugging */ function getTokenKindDesc(kind) { return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind; }
the_stack
import { checkExpr, checkPredicate, checkVar, disambiguateSubNode, } from "compiler/Substance"; import consola, { LogLevel } from "consola"; import { constrDict, objDict } from "contrib/Constraints"; // Dicts (runtime data) import { compDict } from "contrib/Functions"; import { constOf, numOf, varOf } from "engine/Autodiff"; import { addWarn, defaultLbfgsParams, dummyASTNode, dummyIdentifier, findExpr, findExprSafe, initConstraintWeight, insertExpr, insertExprs, insertGPI, isPath, isTagExpr, valueNumberToAutodiffConst, } from "engine/EngineUtils"; import { alg, Graph } from "graphlib"; import _ from "lodash"; import nearley from "nearley"; import { lastLocation } from "parser/ParserUtil"; import styleGrammar from "parser/StyleParser"; import { Canvas, findDef, PropType, Sampler, ShapeDef, shapedefs, } from "renderer/ShapeDef"; import rfdc from "rfdc"; import { VarAD } from "types/ad"; import { Identifier } from "types/ast"; import { Either, Just, Left, MaybeVal, Right } from "types/common"; import { ConstructorDecl, Env, TypeConstructor } from "types/domain"; import { ParseError, PenroseError, StyleError, StyleErrors, StyleResults, StyleWarnings, SubstanceError, } from "types/errors"; import { Fn, OptType, Params, State } from "types/state"; import { BindingForm, Block, DeclPattern, Expr, GPIDecl, Header, HeaderBlock, IAccessPath, ICompApp, IConstrFn, ILayering, IObjFn, Path, PredArg, PropertyDecl, RelationPattern, RelBind, RelPred, Selector, SelExpr, Stmt, StyProg, StyT, StyVar, } from "types/style"; import { LocalVarSubst, ProgType, SelEnv, Subst } from "types/styleSemantics"; import { ApplyConstructor, ApplyPredicate, LabelMap, SubExpr, SubPredArg, SubProg, SubstanceEnv, SubStmt, TypeConsApp, } from "types/substance"; import { FExpr, Field, FieldDict, FieldExpr, GPIMap, GPIProps, IFGPI, IOptEval, Property, PropID, ShapeTypeStr, StyleOptFn, TagExpr, Translation, Value, } from "types/value"; import { err, isErr, ok, parseError, Result, toStyleErrors } from "utils/Error"; import { prettyPrintPath } from "utils/OtherUtils"; import { randFloat } from "utils/Util"; import { checkTypeConstructor, isDeclaredSubtype } from "./Domain"; const log = consola .create({ level: LogLevel.Warn }) .withScope("Style Compiler"); const clone = rfdc({ proto: false, circles: false }); //#region consts const ANON_KEYWORD = "ANON"; const LOCAL_KEYWORD = "$LOCAL"; const LABEL_FIELD = "label"; const UnknownTagError = new Error("unknown tag"); const VARYING_INIT_FN_NAME = "VARYING_INIT"; // For statically checking existence const FN_DICT = { CompApp: compDict, ObjFn: objDict, ConstrFn: constrDict, }; const FN_ERR_TYPE = { CompApp: "InvalidFunctionNameError" as const, ObjFn: "InvalidObjectiveNameError" as const, ConstrFn: "InvalidConstraintNameError" as const, }; //#endregion //#region utils const dummyId = (name: string): Identifier => dummyIdentifier(name, "SyntheticStyle"); // numbers from 0 to r-1 w/ increment of 1 const numbers = (r: number): number[] => { const l = 0; if (l > r) { throw Error("invalid range"); } const arr = []; for (let i = l; i < r; i++) { arr.push(i); } return arr; }; export function numbered<A>(xs: A[]): [A, number][] { if (!xs) throw Error("fail"); return _.zip(xs, numbers(xs.length)) as [A, number][]; // COMBAK: Don't know why typescript has problem with this } // TODO move to util export function isLeft<A>(val: any): val is Left<A> { if ((val as Left<A>).tag === "Left") return true; return false; } export function isRight<B>(val: any): val is Right<B> { if ((val as Right<B>).tag === "Right") return true; return false; } export function toLeft<A>(val: A): Left<A> { return { contents: val, tag: "Left" }; } export function toRight<B>(val: B): Right<B> { return { contents: val, tag: "Right" }; } export function ToLeft<A, B>(val: A): Either<A, B> { return { contents: val, tag: "Left" }; } export function ToRight<A, B>(val: B): Either<A, B> { return { contents: val, tag: "Right" }; } export function foldM<A, B, C>( xs: A[], f: (acc: B, curr: A, i: number) => Either<C, B>, init: B ): Either<C, B> { let res = init; let resW: Either<C, B> = toRight(init); // wrapped for (let i = 0; i < xs.length; i++) { resW = f(res, xs[i], i); if (resW.tag === "Left") { return resW; } // Stop fold early on first error and return it res = resW.contents; } return resW; } function justs<T>(xs: MaybeVal<T>[]): T[] { return xs .filter((x) => x.tag === "Just") .map((x) => { if (x.tag === "Just") { return x.contents; } throw Error("unexpected"); // Shouldn't happen }); } const safeContentsList = (x: any) => (x ? x.contents : []); const toString = (x: BindingForm): string => x.contents.value; // https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript const cartesianProduct = (...a: any[]) => a.reduce((a, b) => a.flatMap((d: any) => b.map((e: any) => [d, e].flat()))); const pathString = (p: Path): string => { // COMBAK: This should be replaced by prettyPrintPath if (p.tag === "FieldPath") { return `${p.name.contents.value}.${p.field.value}`; } else if (p.tag === "PropertyPath") { return `${p.name.contents.value}.${p.field.value}.${p.property.value}`; } else throw Error("pathStr not implemented"); }; const getShapeName = (s: string, f: Field): string => { return `${s}.${f}`; }; //#endregion //#region Some code for prettyprinting const ppExpr = (e: SelExpr): string => { if (e.tag === "SEBind") { return e.contents.contents.value; } else if (["SEFunc", "SEValCons", "SEFuncOrValCons"].includes(e.tag)) { const args = e.args.map(ppExpr); return `${e.name.value}(${args})`; } else if (((e as any) as StyVar).tag === "StyVar") { return ((e as any) as StyVar).contents.value; } else { console.log("res", e); throw Error("unknown tag"); } }; const ppRelArg = (r: PredArg): string => { if (r.tag === "RelPred") { return ppRelPred(r); } else { return ppExpr(r); } }; const ppRelBind = (r: RelBind): string => { const expr = ppExpr(r.expr); return `${r.id.contents.value} := ${expr}`; }; const ppRelPred = (r: RelPred): string => { const args = r.args.map(ppRelArg).join(", "); const name = r.name.value; return `${name}(${args})`; }; export const ppRel = (r: RelationPattern): string => { if (r.tag === "RelBind") { return ppRelBind(r); } else if (r.tag === "RelPred") { return ppRelPred(r); } else throw Error("unknown tag"); }; //#endregion //#region Types and code for selector checking and environment construction const initSelEnv = (): SelEnv => { // Note that JS objects are by reference, so you have to make a new one each time return { sTypeVarMap: {}, varProgTypeMap: {}, skipBlock: false, header: { tag: "Nothing" }, warnings: [], errors: [], }; }; // Add a mapping from Sub or Sty var to the selector's environment // g, (x : |T) // NOTE: Mutates the map in `m` const addMapping = ( k: BindingForm, v: StyT, m: SelEnv, p: ProgType ): SelEnv => { m.sTypeVarMap[toString(k)] = v; m.varProgTypeMap[toString(k)] = [p, k]; return m; }; // add warning/error to end of existing errors in selector env const addErrSel = (selEnv: SelEnv, err: StyleError): SelEnv => { return { ...selEnv, errors: selEnv.errors.concat([err]), }; }; // TODO: Test this // Judgment 3. G; g |- |S_o ok ~> g' // `checkDeclPattern` const checkDeclPatternAndMakeEnv = ( varEnv: Env, selEnv: SelEnv, stmt: DeclPattern ): SelEnv => { const [styType, bVar] = [stmt.type, stmt.id]; const typeErr = checkTypeConstructor(toSubstanceType(styType), varEnv); if (isErr(typeErr)) { // TODO(errors) return addErrSel(selEnv, { tag: "TaggedSubstanceError", error: typeErr.error, }); } const varName: string = bVar.contents.value; // TODO(errors) if (Object.keys(selEnv.sTypeVarMap).includes(varName)) { return addErrSel(selEnv, { tag: "SelectorVarMultipleDecl", varName: bVar }); } if (bVar.tag === "StyVar") { // rule Decl-Sty-Context // NOTE: this does not aggregate *all* possible errors. May just return first error. // y \not\in dom(g) return addMapping(bVar, styType, selEnv, { tag: "StyProgT" }); } else if (bVar.tag === "SubVar") { // rule Decl-Sub-Context // x \not\in dom(g) const substanceType = varEnv.vars.get(varName); // If any Substance variable doesn't exist in env, ignore it, // but flag it so we know to not translate the lines in the block later. if (!substanceType) { return { ...selEnv, skipBlock: true }; } // check "T <: |T", assuming type constructors are nullary // Specifically, the Style type for a Substance var needs to be more general. Otherwise, if it's more specific, that's a coercion // e.g. this is correct: Substance: "SpecialVector `v`"; Style: "Vector `v`" const declType = toSubstanceType(styType); if (!isDeclaredSubtype(substanceType, declType, varEnv)) { // COMBAK: Order? // TODO(errors) return addErrSel(selEnv, { tag: "SelectorDeclTypeMismatch", subType: declType, styType: substanceType, }); } return addMapping(bVar, styType, selEnv, { tag: "SubProgT" }); } else throw Error("unknown tag"); }; // Judgment 6. G; g |- [|S_o] ~> g' // `checkDeclPatterns` w/o error-checking, just addMapping for StyVars and SubVars const checkDeclPatternsAndMakeEnv = ( varEnv: Env, selEnv: SelEnv, decls: DeclPattern[] ): SelEnv => { return decls.reduce( (s, p) => checkDeclPatternAndMakeEnv(varEnv, s, p), selEnv ); }; // TODO: Test this function // Judgment 4. G |- |S_r ok const checkRelPattern = (varEnv: Env, rel: RelationPattern): StyleErrors => { // rule Bind-Context if (rel.tag === "RelBind") { // TODO: use checkSubStmt here (and in paper)? // TODO: make sure the ill-typed bind selectors fail here (after Sub statics is fixed) // G |- B : T1 const res1 = checkVar(rel.id.contents, varEnv); // TODO(error) if (isErr(res1)) { const subErr1: SubstanceError = res1.error; // TODO(error): Do we need to wrap this error further, or is returning SubstanceError with no additional Style info ok? // return ["substance typecheck error in B"]; return [{ tag: "TaggedSubstanceError", error: subErr1 }]; } const [vtype, env1] = res1.value; // G |- E : T2 const res2 = checkExpr(toSubExpr(varEnv, rel.expr), varEnv); // TODO(error) if (isErr(res2)) { const subErr2: SubstanceError = res2.error; return [{ tag: "TaggedSubstanceError", error: subErr2 }]; // return ["substance typecheck error in E"]; } const [etype, env2] = res2.value; // T1 = T2 const typesEq = isDeclaredSubtype(vtype, etype, varEnv); // TODO(error) -- improve message if (!typesEq) { return [ { tag: "SelectorRelTypeMismatch", varType: vtype, exprType: etype }, ]; // return ["types not equal"]; } return []; } else if (rel.tag === "RelPred") { // rule Pred-Context // G |- Q : Prop const res = checkPredicate(toSubPred(rel), varEnv); if (isErr(res)) { const subErr3: SubstanceError = res.error; return [{ tag: "TaggedSubstanceError", error: subErr3 }]; // return ["substance typecheck error in Pred"]; } return []; } else { throw Error("unknown tag"); } }; // Judgment 5. G |- [|S_r] ok const checkRelPatterns = ( varEnv: Env, rels: RelationPattern[] ): StyleErrors => { return _.flatMap( rels, (rel: RelationPattern): StyleErrors => checkRelPattern(varEnv, rel) ); }; const toSubstanceType = (styT: StyT): TypeConsApp => { // TODO: Extend for non-nullary types (when they are implemented in Style) return { tag: "TypeConstructor", name: styT, args: [], }; }; // TODO: Test this // NOTE: `Map` is immutable; we return the same `Env` reference with a new `vars` set (rather than mutating the existing `vars` Map) const mergeMapping = ( varProgTypeMap: { [k: string]: [ProgType, BindingForm] }, varEnv: Env, [varName, styType]: [string, StyT] ): Env => { const res = varProgTypeMap[varName]; if (!res) { throw Error("var has no binding form?"); } const [progType, bindingForm] = res; if (bindingForm.tag === "SubVar") { // G || (x : |T) |-> G return varEnv; } else if (bindingForm.tag === "StyVar") { // G || (y : |T) |-> G[y : T] (shadowing any existing Sub vars) return { ...varEnv, vars: varEnv.vars.set( bindingForm.contents.value, toSubstanceType(styType) ), }; } else { throw Error("unknown tag"); } }; // TODO: don't merge the varmaps! just put g as the varMap (otherwise there will be extraneous bindings for the relational statements) // Judgment 1. G || g |-> ... const mergeEnv = (varEnv: Env, selEnv: SelEnv): Env => { return Object.entries(selEnv.sTypeVarMap).reduce( (acc, curr) => mergeMapping(selEnv.varProgTypeMap, acc, curr), varEnv ); }; // ported from `checkPair`, `checkSel`, and `checkNamespace` const checkHeader = (varEnv: Env, header: Header): SelEnv => { if (header.tag === "Selector") { // Judgment 7. G |- Sel ok ~> g const sel: Selector = header; const selEnv_afterHead = checkDeclPatternsAndMakeEnv( varEnv, initSelEnv(), sel.head.contents ); // Check `with` statements // TODO: Did we get rid of `with` statements? const selEnv_decls = checkDeclPatternsAndMakeEnv( varEnv, selEnv_afterHead, safeContentsList(sel.with) ); const relErrs = checkRelPatterns( mergeEnv(varEnv, selEnv_decls), safeContentsList(sel.where) ); // TODO(error): The errors returned in the top 3 statements return { ...selEnv_decls, errors: selEnv_decls.errors.concat(relErrs), // COMBAK: Reverse the error order? }; } else if (header.tag === "Namespace") { // TODO(error) return initSelEnv(); } else throw Error("unknown Style header tag"); }; // Returns a sel env for each selector in the Style program, in the same order // previously named `checkSels` export const checkSelsAndMakeEnv = ( varEnv: Env, prog: HeaderBlock[] ): SelEnv[] => { // Note that even if there is an error in one selector, it does not stop checking of the other selectors const selEnvs: SelEnv[] = prog.map((e) => { const res = checkHeader(varEnv, e.header); // Put selector AST in just for debugging res.header = { tag: "Just", contents: e.header }; return res; }); return selEnvs; }; //#endregion //#region Types and code for finding substitutions // Judgment 20. A substitution for a selector is only correct if it gives exactly one // mapping for each Style variable in the selector. (Has test) export const fullSubst = (selEnv: SelEnv, subst: Subst): boolean => { // Check if a variable is a style variable, not a substance one const isStyVar = (e: string): boolean => selEnv.varProgTypeMap[e][0].tag === "StyProgT"; // Equal up to permutation (M.keys ensures that there are no dups) const selStyVars = Object.keys(selEnv.sTypeVarMap).filter(isStyVar); const substStyVars = Object.keys(subst); // Equal up to permutation (keys of an object in js ensures that there are no dups) return _.isEqual(selStyVars.sort(), substStyVars.sort()); }; // Check that there are no duplicate keys or vals in the substitution export const uniqueKeysAndVals = (subst: Subst): boolean => { // All keys already need to be unique in js, so only checking values const vals = Object.values(subst); const valsSet = {}; for (let i = 0; i < vals.length; i++) { valsSet[vals[i]] = 0; // This 0 means nothing, we just want to create a set of values } // All entries were unique if length didn't change (ie the nub didn't change) return Object.keys(valsSet).length === vals.length; }; // Optimization to filter out Substance statements that have no hope of matching any of the substituted relation patterns, so we don't do redundant work for every substitution (of which there could be millions). This function is only called once per selector. const couldMatchRels = ( typeEnv: Env, rels: RelationPattern[], stmt: SubStmt ): boolean => { // TODO < (this is an optimization; will only implement if needed) return true; }; //#region (subregion? TODO fix) Applying a substitution // // Apply a substitution to various parts of Style (relational statements, exprs, blocks) // Recursively walk the tree, looking up and replacing each Style variable encountered with a Substance variable // If a Sty var doesn't have a substitution (i.e. substitution map is bad), keep the Sty var and move on // COMBAK: return "maybe" if a substitution fails? // COMBAK: Add a type for `lv`? It's not used here const substituteBform = ( lv: any, subst: Subst, bform: BindingForm ): BindingForm => { // theta(B) = ... if (bform.tag === "SubVar") { // Variable in backticks in block or selector (e.g. `X`), so nothing to substitute return bform; } else if (bform.tag === "StyVar") { // Look up the substitution for the Style variable and return a Substance variable // Returns result of mapping if it exists (y -> x) const res = subst[bform.contents.value]; if (res) { return { ...bform, // Copy the start/end loc of the original Style variable, since we don't have Substance parse info (COMBAK) tag: "SubVar", contents: { ...bform.contents, // Copy the start/end loc of the original Style variable, since we don't have Substance parse info type: "value", value: res, // COMBAK: double check please }, }; } else { // Nothing to substitute return bform; } } else throw Error("unknown tag"); }; const substituteExpr = (subst: Subst, expr: SelExpr): SelExpr => { // theta(B) = ... if (expr.tag === "SEBind") { return { ...expr, contents: substituteBform({ tag: "Nothing" }, subst, expr.contents), }; } else if (["SEFunc", "SEValCons", "SEFuncOrValCons"].includes(expr.tag)) { // COMBAK: Remove SEFuncOrValCons? // theta(f[E]) = f([theta(E)] return { ...expr, args: expr.args.map((arg) => substituteExpr(subst, arg)), }; } else { throw Error("unsupported tag"); } }; const substitutePredArg = (subst: Subst, predArg: PredArg): PredArg => { if (predArg.tag === "RelPred") { return { ...predArg, args: predArg.args.map((arg) => substitutePredArg(subst, arg)), }; } else if (predArg.tag === "SEBind") { return { ...predArg, contents: substituteBform({ tag: "Nothing" }, subst, predArg.contents), // COMBAK: Why is bform here... }; } else { console.log("unknown tag", subst, predArg); throw Error("unknown tag"); } }; // theta(|S_r) = ... export const substituteRel = ( subst: Subst, rel: RelationPattern ): RelationPattern => { if (rel.tag === "RelBind") { // theta(B := E) |-> theta(B) := theta(E) return { ...rel, id: substituteBform({ tag: "Nothing" }, subst, rel.id), expr: substituteExpr(subst, rel.expr), }; } else if (rel.tag === "RelPred") { // theta(Q([a]) = Q([theta(a)]) return { ...rel, args: rel.args.map((arg) => substitutePredArg(subst, arg)), }; } else throw Error("unknown tag"); }; // Applies a substitution to a list of relational statement theta([|S_r]) // TODO: assumes a full substitution const substituteRels = ( subst: Subst, rels: RelationPattern[] ): RelationPattern[] => { const res = rels.map((rel) => substituteRel(subst, rel)); return res; }; //#endregion (subregion? TODO fix) //#region Applying a substitution to a block // // Substs for the translation semantics (more tree-walking on blocks, just changing binding forms) const mkLocalVarName = (lv: LocalVarSubst): string => { if (lv.tag === "LocalVarId") { const [blockNum, substNum] = lv.contents; return `${LOCAL_KEYWORD}_block${blockNum}_subst${substNum}`; } else if (lv.tag === "NamespaceId") { return lv.contents; } else throw Error("unknown error"); }; const substitutePath = (lv: LocalVarSubst, subst: Subst, path: Path): Path => { if (path.tag === "FieldPath") { return { ...path, name: substituteBform({ tag: "Just", contents: lv }, subst, path.name), }; } else if (path.tag === "PropertyPath") { return { ...path, name: substituteBform({ tag: "Just", contents: lv }, subst, path.name), }; } else if (path.tag === "LocalVar") { return { nodeType: "SyntheticStyle", children: [], tag: "FieldPath", name: { children: [], nodeType: "SyntheticStyle", tag: "SubVar", contents: { ...dummyId(mkLocalVarName(lv)), }, }, field: path.contents, }; } else if (path.tag === "InternalLocalVar") { // Note that the local var becomes a path // Use of local var 'v' (on right-hand side of '=' sign in Style) gets transformed into field path reference '$LOCAL_<ids>.v' // where <ids> is a string generated to be unique to this selector match for this block // COMBAK / HACK: Is there some way to get rid of all these dummy values? return { nodeType: "SyntheticStyle", children: [], tag: "FieldPath", name: { nodeType: "SyntheticStyle", children: [], tag: "SubVar", contents: { ...dummyId(mkLocalVarName(lv)), }, }, field: dummyId(path.contents), }; } else if (path.tag === "AccessPath") { // COMBAK: Check if this works / is needed (wasn't present in original code) return { ...path, path: substitutePath(lv, subst, path.path), }; } else { throw Error("unknown tag"); } }; const substituteField = ( lv: LocalVarSubst, subst: Subst, field: PropertyDecl ): PropertyDecl => { return { ...field, value: substituteBlockExpr(lv, subst, field.value), }; }; const substituteBlockExpr = ( lv: LocalVarSubst, subst: Subst, expr: Expr ): Expr => { if (isPath(expr)) { return substitutePath(lv, subst, expr); } else if ( expr.tag === "CompApp" || expr.tag === "ObjFn" || expr.tag === "ConstrFn" ) { // substitute out occurrences of `VARYING_INIT(i)` (the computation) for `VaryingInit(i)` (the `AnnoFloat`) as there is currently no special syntax for this // note that this is a hack; instead of shoehorning it into `substituteBlockExpr`, it should be done more cleanly as a compiler pass on the Style block AST at some point. doesn't really matter when this is done as long as it's before the varying float initialization in `genState if (expr.tag === "CompApp") { if (expr.name.value === VARYING_INIT_FN_NAME) { // TODO(err): Typecheck VARYING_INIT properly and return an error. This will be unnecessary if parsed with special syntax. if (expr.args.length !== 1) { throw Error("expected one argument to VARYING_INIT"); } if (expr.args[0].tag !== "Fix") { throw Error("expected float argument to VARYING_INIT"); } return { ...dummyASTNode({}, "SyntheticStyle"), tag: "VaryInit", contents: expr.args[0].contents, }; } } return { ...expr, args: expr.args.map((arg: Expr) => substituteBlockExpr(lv, subst, arg)), }; } else if (expr.tag === "BinOp") { return { ...expr, left: substituteBlockExpr(lv, subst, expr.left), right: substituteBlockExpr(lv, subst, expr.right), }; } else if (expr.tag === "UOp") { return { ...expr, arg: substituteBlockExpr(lv, subst, expr.arg), }; } else if ( expr.tag === "List" || expr.tag === "Vector" || expr.tag === "Matrix" ) { return { ...expr, contents: expr.contents.map((e: Expr) => substituteBlockExpr(lv, subst, e) ), }; } else if (expr.tag === "ListAccess") { return { ...expr, contents: [substitutePath(lv, subst, expr.contents[0]), expr.contents[1]], }; } else if (expr.tag === "GPIDecl") { return { ...expr, properties: expr.properties.map((p: PropertyDecl) => substituteField(lv, subst, p) ), }; } else if (expr.tag === "Layering") { return { ...expr, below: substitutePath(lv, subst, expr.below), above: substitutePath(lv, subst, expr.above), }; } else if (expr.tag === "PluginAccess") { return { ...expr, contents: [ expr.contents[0], substituteBlockExpr(lv, subst, expr.contents[1]), substituteBlockExpr(lv, subst, expr.contents[2]), ], }; } else if (expr.tag === "Tuple") { return { ...expr, contents: [ substituteBlockExpr(lv, subst, expr.contents[0]), substituteBlockExpr(lv, subst, expr.contents[1]), ], }; } else if (expr.tag === "VectorAccess") { return { ...expr, contents: [ substitutePath(lv, subst, expr.contents[0]), substituteBlockExpr(lv, subst, expr.contents[1]), ], }; } else if (expr.tag === "MatrixAccess") { return { ...expr, contents: [ substitutePath(lv, subst, expr.contents[0]), expr.contents[1].map((e) => substituteBlockExpr(lv, subst, e)), ], }; } else if ( expr.tag === "Fix" || expr.tag === "Vary" || expr.tag === "VaryAD" || // technically is not present at this stage expr.tag === "VaryInit" || expr.tag === "StringLit" || expr.tag === "BoolLit" ) { // No substitution for literals return expr; } else { console.error("expr", expr); throw Error("unknown tag"); } }; const substituteLine = (lv: LocalVarSubst, subst: Subst, line: Stmt): Stmt => { if (line.tag === "PathAssign") { return { ...line, path: substitutePath(lv, subst, line.path), value: substituteBlockExpr(lv, subst, line.value), }; } else if (line.tag === "Override") { return { ...line, path: substitutePath(lv, subst, line.path), value: substituteBlockExpr(lv, subst, line.value), }; } else if (line.tag === "Delete") { return { ...line, contents: substitutePath(lv, subst, line.contents), }; } else { throw Error( "Case should not be reached (anonymous statement should be substituted for a local one in `nameAnonStatements`)" ); } }; // Assumes a full substitution const substituteBlock = ( [subst, si]: [Subst, number], [block, bi]: [Block, number], name: MaybeVal<string> ): Block => { const lvSubst: LocalVarSubst = name.tag === "Nothing" ? { tag: "LocalVarId", contents: [bi, si] } : { tag: "NamespaceId", contents: name.contents }; return { ...block, statements: block.statements.map((line) => substituteLine(lvSubst, subst, line) ), }; }; //#endregion Applying a substitution to a block // Convert Style expression to Substance expression (for ease of comparison in matching) // Note: the env is needed to disambiguate SEFuncOrValCons const toSubExpr = (env: Env, e: SelExpr): SubExpr => { if (e.tag === "SEBind") { return e.contents.contents; } else if (e.tag === "SEFunc") { return { ...e, // Puts the remnants of e's ASTNode info here -- is that ok? tag: "ApplyFunction", name: e.name, args: e.args.map((e) => toSubExpr(env, e)), }; } else if (e.tag === "SEValCons") { return { ...e, tag: "ApplyConstructor", name: e.name, args: e.args.map((e) => toSubExpr(env, e)), }; } else if (e.tag === "SEFuncOrValCons") { const res = { ...e, tag: "Func", // Use the generic Substance parse type so on conversion, it can be disambiguated by `disambiguateFunctions` name: e.name, args: e.args.map((e) => toSubExpr(env, e)), }; disambiguateSubNode(env, res); // mutates res return res as SubExpr; } else throw Error("unknown tag"); }; const toSubPredArg = (a: PredArg): SubPredArg => { if (a.tag === "SEBind") { return a.contents.contents; } else if (a.tag === "RelPred") { return toSubPred(a); } else throw Error("unknown tag"); }; // Convert Style predicate to Substance predicate (for ease of comparison in matching) const toSubPred = (p: RelPred): ApplyPredicate => { return { ...p, tag: "ApplyPredicate", name: p.name, args: p.args.map(toSubPredArg), }; }; const varsEq = (v1: Identifier, v2: Identifier): boolean => { return v1.value === v2.value; }; const subVarsEq = (v1: Identifier, v2: Identifier): boolean => { return v1.value === v2.value; }; const argsEq = (a1: SubPredArg, a2: SubPredArg): boolean => { if (a1.tag === "ApplyPredicate" && a2.tag === "ApplyPredicate") { return subFnsEq(a1, a2); } else if (a1.tag === a2.tag) { // both are SubExpr, which are not explicitly tagged return subExprsEq(a1 as SubExpr, a2 as SubExpr); } else return false; // they are different types }; const subFnsEq = (p1: any, p2: any): boolean => { if ( !p1.hasOwnProperty("name") || !p1.hasOwnProperty("args") || !p2.hasOwnProperty("name") || !p2.hasOwnProperty("args") ) { throw Error("expected substance type with name and args properties"); } if (p1.args.length !== p2.args.length) { return false; } // Can use `as` because now we know their lengths are equal const allArgsEq = _.zip(p1.args, p2.args).every(([a1, a2]) => argsEq(a1 as SubPredArg, a2 as SubPredArg) ); return p1.name.value === p2.name.value && allArgsEq; }; const subExprsEq = (e1: SubExpr, e2: SubExpr): boolean => { // ts doesn't seem to work well with the more generic way of checking this if (e1.tag === "Identifier" && e2.tag === "Identifier") { return e1.value === e2.value; } else if ( (e1.tag === "ApplyFunction" && e2.tag === "ApplyFunction") || (e1.tag === "ApplyConstructor" && e2.tag === "ApplyConstructor") || (e1.tag === "Func" && e2.tag === "Func") ) { return subFnsEq(e1, e2); } else if (e1.tag === "Deconstructor" && e2.tag === "Deconstructor") { return ( e1.variable.value === e2.variable.value && e1.field.value === e2.field.value ); } else if (e1.tag === "StringLit" && e2.tag === "StringLit") { return e1.contents === e2.contents; } return false; }; const exprToVar = (e: SubExpr): Identifier => { if (e.tag === "Identifier") { return e; } else { // TODO(errors) throw Error( "internal error: Style expression matching doesn't yet handle nested exprssions" ); } }; const toTypeList = (c: ConstructorDecl): TypeConstructor[] => { return c.args.map((p) => { if (p.type.tag === "TypeConstructor") { return p.type; } throw Error( "internal error: expected TypeConstructor in type (expected nullary type)" ); }); }; // TODO: Test this // For existing judgment G |- T1 <: T2, // this rule (SUBTYPE-ARROW) checks if the first arrow type (i.e. function or value constructor type) is a subtype of the second // The arrow types are contravariant in their arguments and covariant in their return type // e.g. if Cat <: Animal, then Cat -> Cat <: Cat -> Animal, and Animal -> Cat <: Cat -> Cat const isSubtypeArrow = ( types1: TypeConstructor[], types2: TypeConstructor[], e: Env ): boolean => { if (types1.length !== types2.length) { return false; } if (types1.length === 0 && types2.length === 0) { return true; } return ( isDeclaredSubtype(types2[0], types1[0], e) && // Note swap -- contravariant in arguments isSubtypeArrow(types1.slice(1), types2.slice(1), e) ); // Covariant in return type }; const exprsMatchArr = ( varEnv: Env, subE: ApplyConstructor, styE: ApplyConstructor ): boolean => { const subArrType = varEnv.constructors.get(subE.name.value); if (!subArrType) { // TODO(errors) throw Error("internal error: sub arr type doesn't exist"); } const styArrType = varEnv.constructors.get(styE.name.value); if (!styArrType) { // TODO(errors) throw Error("internal error: sty arr type doesn't exist"); } if (subE.args.length !== styE.args.length) { return false; } const subArrTypes = toTypeList(subArrType); const styArrTypes = toTypeList(styArrType); const subVarArgs = subE.args.map(exprToVar); const styVarArgs = styE.args.map(exprToVar); return ( isSubtypeArrow(subArrTypes, styArrTypes, varEnv) && _.zip(subVarArgs, styVarArgs).every(([a1, a2]) => varsEq(a1 as Identifier, a2 as Identifier) ) ); // `as` is fine bc of preceding length check }; // New judgment (number?): expression matching that accounts for subtyping. G, B, . |- E0 <| E1 // We assume the latter expression has already had a substitution applied const exprsMatch = (typeEnv: Env, subE: SubExpr, selE: SubExpr): boolean => { // We match value constructor applications if one val ctor is a subtype of another // whereas for function applications, we match only if the exprs are equal (for now) // This is because a val ctor doesn't "do" anything besides wrap its values // whereas functions with the same type could do very different things, so we don't // necessarily want to match them by subtyping // (e.g. think of the infinite functions from Vector -> Vector) // rule Match-Expr-Var if (subE.tag === "Identifier" && selE.tag === "Identifier") { return subVarsEq(subE, selE); } else if (subE.tag === "ApplyFunction" && selE.tag === "ApplyFunction") { // rule Match-Expr-Fnapp return subExprsEq(subE, selE); } else if ( subE.tag === "ApplyConstructor" && selE.tag === "ApplyConstructor" ) { // rule Match-Expr-Vconsapp return exprsMatchArr(typeEnv, subE, selE); } else { return false; } }; // Judgment 11. b; theta |- S <| |S_r // After all Substance variables from a Style substitution are substituted in, check if const relMatchesLine = ( typeEnv: Env, subEnv: SubstanceEnv, s1: SubStmt, s2: RelationPattern ): boolean => { if (s1.tag === "Bind" && s2.tag === "RelBind") { // rule Bind-Match const bvar = s2.id; if (s2.id.tag === "StyVar") { // internal error throw Error( `Style variable ${ s2.id.contents.value } found in relational statement ${ppRel(s2)}. Should not be present!` ); } else if (s2.id.tag === "SubVar") { // B |- E = |E const [subVar, sVar] = [s1.variable, s2.id.contents.value]; const selExpr = toSubExpr(typeEnv, s2.expr); const subExpr = s1.expr; return ( subVarsEq(subVar, dummyId(sVar)) && exprsMatch(typeEnv, subExpr, selExpr) ); // COMBAK: Add this condition when this is implemented in the Substance typechecker // || exprsDeclaredEqual(subEnv, expr, selExpr); // B |- E = |E } else throw Error("unknown tag"); } else if (s1.tag === "ApplyPredicate" && s2.tag === "RelPred") { // rule Pred-Match const [pred, sPred] = [s1, s2]; const selPred = toSubPred(sPred); return subFnsEq(pred, selPred); // COMBAK: Add this condition when the Substance typechecker is implemented -- where is the equivalent function to `predsDeclaredEqual` in the new code? // || C.predsDeclaredEqual subEnv pred selPred // B |- Q <-> |Q } else { return false; // Only match two bind lines or two predicate lines } }; // Judgment 13. b |- [S] <| |S_r const relMatchesProg = ( typeEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, rel: RelationPattern ): boolean => { return subProg.statements.some((line) => relMatchesLine(typeEnv, subEnv, line, rel) ); }; // Judgment 15. b |- [S] <| [|S_r] const allRelsMatch = ( typeEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, rels: RelationPattern[] ): boolean => { return rels.every((rel) => relMatchesProg(typeEnv, subEnv, subProg, rel)); }; // Judgment 17. b; [theta] |- [S] <| [|S_r] ~> [theta'] // Folds over [theta] const filterRels = ( typeEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, rels: RelationPattern[], substs: Subst[] ): Subst[] => { const subProgFiltered: SubProg = { ...subProg, statements: subProg.statements.filter((line) => couldMatchRels(typeEnv, rels, line) ), }; return substs.filter((subst) => allRelsMatch(typeEnv, subEnv, subProgFiltered, substituteRels(subst, rels)) ); }; // // Match declaration statements // // Substitution helper functions // (+) operator combines two substitutions: subst -> subst -> subst const combine = (s1: Subst, s2: Subst): Subst => { return { ...s1, ...s2 }; }; // TODO check for duplicate keys (and vals) // (x) operator combines two lists of substitutions: [subst] -> [subst] -> [subst] // the way merge is used, I think each subst in the second argument only contains one mapping const merge = (s1: Subst[], s2: Subst[]): Subst[] => { if (s2.length === 0) { return s1; } if (s1.length === 0) { return s2; } return cartesianProduct(s1, s2).map(([a, b]: Subst[]) => combine(a, b)); }; // Judgment 9. G; theta |- T <| |T // Assumes types are nullary, so doesn't return a subst, only a bool indicating whether the types matched // Ported from `matchType` const typesMatched = ( varEnv: Env, substanceType: TypeConsApp, styleType: StyT ): boolean => { if ( substanceType.tag === "TypeConstructor" && substanceType.args.length === 0 ) { // Style type needs to be more generic than Style type return isDeclaredSubtype(substanceType, toSubstanceType(styleType), varEnv); } // TODO(errors) console.log(substanceType, styleType); throw Error( "internal error: expected two nullary types (parametrized types to be implemented)" ); }; // Judgment 10. theta |- x <| B const matchBvar = (subVar: Identifier, bf: BindingForm): MaybeVal<Subst> => { if (bf.tag === "StyVar") { const newSubst = {}; newSubst[toString(bf)] = subVar.value; // StyVar matched SubVar return { tag: "Just", contents: newSubst, }; } else if (bf.tag === "SubVar") { if (subVar.value === bf.contents.value) { // Substance variables matched; comparing string equality return { tag: "Just", contents: {}, }; } else { return { tag: "Nothing" }; // TODO: Note, here we distinguish between an empty substitution and no substitution... but why? } } else throw Error("unknown tag"); }; // Judgment 12. G; theta |- S <| |S_o // TODO: Not sure why Maybe<Subst> doesn't work in the type signature? const matchDeclLine = ( varEnv: Env, line: SubStmt, decl: DeclPattern ): MaybeVal<Subst> => { if (line.tag === "Decl") { const [subT, subVar] = [line.type, line.name]; const [styT, bvar] = [decl.type, decl.id]; // substitution is only valid if types matched first if (typesMatched(varEnv, subT, styT)) { return matchBvar(subVar, bvar); } } // Sty decls only match Sub decls return { tag: "Nothing" }; }; // Judgment 16. G; [theta] |- [S] <| [|S_o] ~> [theta'] const matchDecl = ( varEnv: Env, subProg: SubProg, initSubsts: Subst[], decl: DeclPattern ): Subst[] => { // Judgment 14. G; [theta] |- [S] <| |S_o const newSubsts = subProg.statements.map((line) => matchDeclLine(varEnv, line, decl) ); const res = merge(initSubsts, justs(newSubsts)); // TODO inline // COMBAK: Inline this // console.log("substs to combine:", initSubsts, justs(newSubsts)); // console.log("res", res); return res; }; // Judgment 18. G; [theta] |- [S] <| [|S_o] ~> [theta'] // Folds over [|S_o] const matchDecls = ( varEnv: Env, subProg: SubProg, decls: DeclPattern[], initSubsts: Subst[] ): Subst[] => { return decls.reduce( (substs, decl) => matchDecl(varEnv, subProg, substs, decl), initSubsts ); }; // Judgment 19. g; G; b; [theta] |- [S] <| Sel // NOTE: this uses little gamma (not in paper) to check substitution validity // ported from `find_substs_sel` const findSubstsSel = ( varEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, [header, selEnv]: [Header, SelEnv] ): Subst[] => { if (header.tag === "Selector") { const sel = header; const decls = sel.head.contents.concat(safeContentsList(sel.with)); const rels = safeContentsList(sel.where); const initSubsts: Subst[] = []; const rawSubsts = matchDecls(varEnv, subProg, decls, initSubsts); const substCandidates = rawSubsts.filter((subst) => fullSubst(selEnv, subst) ); const filteredSubsts = filterRels( varEnv, subEnv, subProg, rels, substCandidates ); const correctSubsts = filteredSubsts.filter(uniqueKeysAndVals); return correctSubsts; } else if (header.tag === "Namespace") { // No substitutions for a namespace (not in paper) return []; } else throw Error("unknown tag"); }; // Find a list of substitutions for each selector in the Sty program. (ported from `find_substs_prog`) export const findSubstsProg = ( varEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, styProg: HeaderBlock[], selEnvs: SelEnv[] ): Subst[][] => { if (selEnvs.length !== styProg.length) { throw Error("expected same # selEnvs as selectors"); } const selsWithEnvs = _.zip( styProg.map((e: HeaderBlock) => e.header), selEnvs ); // TODO: Why can't I type it [Header, SelEnv][]? It shouldn't be undefined after the length check return selsWithEnvs.map((selAndEnv) => findSubstsSel(varEnv, subEnv, subProg, selAndEnv as [Header, SelEnv]) ); }; //#endregion //#region Naming anon statements // Style AST preprocessing: // For any anonymous statement only (e.g. `encourage near(x.shape, y.shape)`), // replace it with a named statement (`local.<UNIQUE_ID> = encourage near(x.shape, y.shape)`) // Note the UNIQUE_ID only needs to be unique within a block (since local will assign another ID that's globally-unique) // Leave all other statements unchanged const nameAnonStatement = ( [i, b]: [number, Stmt[]], s: Stmt ): [number, Stmt[]] => { // Transform stmt into local variable assignment "ANON_$counter = e" and increment counter if (s.tag === "AnonAssign") { const stmt: Stmt = { ...s, tag: "PathAssign", type: { tag: "TypeOf", contents: "Nothing" }, // TODO: Why is it parsed like this? path: { tag: "InternalLocalVar", contents: `\$${ANON_KEYWORD}_${i}`, nodeType: "SyntheticStyle", children: [], // Unused bc compiler internal }, value: s.contents, }; return [i + 1, b.concat([stmt])]; } else { return [i, b.concat([s])]; } }; const nameAnonBlock = (b: Block): Block => { return { ...b, statements: b.statements.reduce( (acc, curr) => nameAnonStatement(acc, curr), // Not sure why this can't be point-free [0, []] as [number, Stmt[]] )[1], }; }; export const nameAnonStatements = (prog: StyProg): StyProg => { const p = prog.blocks; return { ...prog, blocks: p.map((hb) => ({ ...hb, block: nameAnonBlock(hb.block) })), }; }; //#endregion //#region Translating Style program const initTrans = (): Translation => { return { trMap: {}, warnings: [] }; }; // /////// Translation judgments /* Note: All of the folds below use foldM. foldM stops accumulating when the first fatal error is reached, using "Either [Error]" as a monad (Non-fatal errors are stored as warnings in the translation) foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a example: f acc elem = if elem < 0 then Left ["wrong " ++ show elem] else Right $ elem : acc foldM f [] [1, 9, -1, 2, -2] = Left ["wrong -1"] foldM f [] [1, 9] = Right [9,1] */ // Judgment 26. D |- phi ~> D' // This is where interesting things actually happen (each line is interpreted and added to the translation) // Related functions in `Evaluator`: findExprSafe, insertExpr // Note this mutates the translation, and we return the translation reference just as a courtesy const deleteProperty = ( trans: Translation, path: Path, // used for ASTNode info name: BindingForm, field: Identifier, property: Identifier ): Translation => { const trn = trans.trMap; const nm = name.contents.value; const fld = field.value; const prp = property.value; const fieldDict = trn[nm]; if (!fieldDict) { // TODO(errors / warnings): Should this be fatal? return addWarn(trans, { tag: "DeletedPropWithNoSubObjError", subObj: name, path, }); } const prop: FieldExpr<VarAD> = fieldDict[fld]; if (!prop) { // TODO(errors / warnings): Should this be fatal? return addWarn(trans, { tag: "DeletedPropWithNoFieldError", subObj: name, field, path, }); } if (prop.tag === "FExpr") { // Deal with GPI aliasing (i.e. only happens if a GPI is aliased to another, and some operation is performed on the aliased GPI's property, it happens to the original) // COMBAK: should path aliasing have destructive effects on the translation (e.g. add or delete)? maybe it should only happen in lookup? Deleting an aliased path should just delete the alias, not its referent? // TODO: Test this if (prop.contents.tag === "OptEval") { if (prop.contents.contents.tag === "FieldPath") { const p = prop.contents.contents; if (varsEq(p.name.contents, name.contents) && varsEq(p.field, field)) { // TODO(error) return addWarn(trans, { tag: "CircularPathAlias", path: { tag: "FieldPath", name, field } as Path, }); } return deleteProperty(trans, p, p.name, p.field, property); } } // TODO(error) return addWarn(trans, { tag: "DeletedPropWithNoGPIError", subObj: name, field, property, path, }); } else if (prop.tag === "FGPI") { // TODO(error, warning): check if the property is member of properties of GPI const gpiDict = prop.contents[1]; delete gpiDict.prp; return trans; } else throw Error("unknown tag"); }; // Note this mutates the translation, and we return the translation reference just as a courtesy const deleteField = ( trans: Translation, path: Path, name: BindingForm, field: Identifier ): Translation => { // TODO(errors): Pass in the original path for error reporting const trn = trans.trMap; const fieldDict = trn[name.contents.value]; if (!fieldDict) { // TODO(errors / warnings) return addWarn(trans, { tag: "DeletedNonexistentFieldError", subObj: name, field, path, }); } if (!(field.value in fieldDict)) { // TODO(errors / warnings) return addWarn(trans, { tag: "DeletedNonexistentFieldError", subObj: name, field, path, }); } delete fieldDict[field.value]; return trans; }; // NOTE: This function mutates the translation // rule Line-delete const deletePath = ( trans: Translation, path: Path ): Either<StyleErrors, Translation> => { if (path.tag === "FieldPath") { const transWithWarnings = deleteField(trans, path, path.name, path.field); return toRight(transWithWarnings); } else if (path.tag === "PropertyPath") { const transWithWarnings = deleteProperty( trans, path, path.name, path.field, path.property ); return toRight(transWithWarnings); } else if (path.tag === "AccessPath") { // TODO(error) const err: StyleError = { tag: "DeletedVectorElemError", path }; return toLeft([err]); } else if (path.tag === "InternalLocalVar") { throw Error( "Compiler should not be deleting a local variable; this should have been removed in a earlier compiler pass" ); } else throw Error("unknown tag"); }; // NOTE: This function mutates the translation const addPath = ( override: boolean, trans: Translation, path: Path, expr: TagExpr<VarAD> ): Either<StyleErrors, Translation> => { // Extended `insertExpr` with an optional flag to deal with errors and warnings // `insertExpr` replaces the old .hs functions `addField` and `addProperty` // Check insertExpr's errors and warnings first const tr2 = insertExpr(path, expr, trans, true, override); if (tr2.warnings.length > 0) { return toLeft(tr2.warnings); } return toRight(tr2); }; const translateLine = ( trans: Translation, stmt: Stmt ): Either<StyleErrors, Translation> => { if (stmt.tag === "PathAssign") { return addPath(false, trans, stmt.path, { tag: "OptEval", contents: stmt.value, }); } else if (stmt.tag === "Override") { return addPath(true, trans, stmt.path, { tag: "OptEval", contents: stmt.value, }); } else if (stmt.tag === "Delete") { return deletePath(trans, stmt.contents); } else throw Error("unknown tag"); }; // Judgment 25. D |- |B ~> D' (modified to be: theta; D |- |B ~> D') const translateBlock = ( name: MaybeVal<string>, blockWithNum: [Block, number], trans: Translation, substWithNum: [Subst, number] ): Either<StyleErrors, Translation> => { const blockSubsted: Block = substituteBlock(substWithNum, blockWithNum, name); return foldM(blockSubsted.statements, translateLine, trans); }; // Judgment 24. [theta]; D |- |B ~> D' // This is a selector, not a namespace, so we substitute local vars with the subst/block IDs const translateSubstsBlock = ( trans: Translation, substsNum: [Subst, number][], blockWithNum: [Block, number] ): Either<StyleErrors, Translation> => { return foldM( substsNum, (trans, substNum, i) => translateBlock({ tag: "Nothing" }, blockWithNum, trans, substNum), trans ); }; //#region Block statics const emptyErrs = () => { return { errors: [], warnings: [] }; }; const oneErr = (err: StyleError): StyleResults => { return { errors: [err], warnings: [] }; }; const combineErrs = (e1: StyleResults, e2: StyleResults): StyleResults => { return { errors: e1.errors.concat(e2.errors), warnings: e1.warnings.concat(e2.warnings), }; }; const flatErrs = (es: StyleResults[]): StyleResults => { return { errors: _.flatMap(es, (e) => e.errors), warnings: _.flatMap(es, (e) => e.warnings), }; }; // Check that every shape name and shape property name in a shape constructor exists const checkGPIInfo = (selEnv: SelEnv, expr: GPIDecl): StyleResults => { const styName: string = expr.shapeName.value; const errors: StyleErrors = []; const warnings: StyleWarnings = []; const shapeNames: string[] = shapedefs.map((e: ShapeDef) => e.shapeType); if (!shapeNames.includes(styName)) { // Fatal error -- we cannot check the shape properties (unless you want to guess the shape) return oneErr({ tag: "InvalidGPITypeError", givenType: expr.shapeName }); } // `findDef` throws an error, so we find the shape name first (done above) to make sure the error can be caught const shapeDef: ShapeDef = findDef(styName); const givenProperties: Identifier[] = expr.properties.map((e) => e.name); const expectedProperties: string[] = Object.entries(shapeDef.properties).map( (e) => e[0] ); for (let gp of givenProperties) { // Check multiple properties, as each one is not fatal if wrong if (!expectedProperties.includes(gp.value)) { errors.push({ tag: "InvalidGPIPropertyError", givenProperty: gp, expectedProperties, }); } } return { errors, warnings }; }; // Check that every function, objective, and constraint exists (below) -- parametrically over the kind of function const checkFunctionName = ( selEnv: SelEnv, expr: ICompApp | IObjFn | IConstrFn ): StyleResults => { const fnDict = FN_DICT[expr.tag]; const fnNames: string[] = _.keys(fnDict); // Names of built-in functions of that kind const givenFnName: Identifier = expr.name; if ( !fnNames.includes(givenFnName.value) && givenFnName.value !== VARYING_INIT_FN_NAME ) { const fnErrorType = FN_ERR_TYPE[expr.tag]; return oneErr({ tag: fnErrorType, givenName: givenFnName }); } return emptyErrs(); }; // Written recursively on exprs, just accumulating possible expr errors const checkBlockExpr = (selEnv: SelEnv, expr: Expr): StyleResults => { // Closure for brevity const check = (e: Expr): StyleResults => checkBlockExpr(selEnv, e); if (isPath(expr)) { return checkBlockPath(selEnv, expr); } else if ( expr.tag === "CompApp" || expr.tag === "ObjFn" || expr.tag === "ConstrFn" ) { const e1 = checkFunctionName(selEnv, expr); const e2 = expr.args.map(check); return flatErrs([e1].concat(e2)); } else if (expr.tag === "BinOp") { return flatErrs([check(expr.left), check(expr.right)]); } else if (expr.tag === "UOp") { return check(expr.arg); } else if ( expr.tag === "List" || expr.tag === "Vector" || expr.tag === "Matrix" ) { return flatErrs(expr.contents.map(check)); } else if (expr.tag === "ListAccess") { return emptyErrs(); } else if (expr.tag === "GPIDecl") { const e1: StyleResults = checkGPIInfo(selEnv, expr); const e2: StyleResults[] = expr.properties.map((p) => check(p.value)); return flatErrs([e1].concat(e2)); } else if (expr.tag === "Layering") { return flatErrs([check(expr.below), check(expr.above)]); } else if (expr.tag === "PluginAccess") { return flatErrs([check(expr.contents[1]), check(expr.contents[2])]); } else if (expr.tag === "Tuple") { return flatErrs([check(expr.contents[0]), check(expr.contents[1])]); } else if (expr.tag === "VectorAccess") { return check(expr.contents[1]); } else if (expr.tag === "MatrixAccess") { return flatErrs(expr.contents[1].map(check)); } else if ( expr.tag === "Fix" || expr.tag === "Vary" || expr.tag === "VaryInit" || expr.tag === "StringLit" || expr.tag === "BoolLit" ) { return emptyErrs(); } else { console.error("expr", expr); throw Error("unknown tag"); } }; const checkBlockPath = (selEnv: SelEnv, path: Path): StyleResults => { // TODO(errors) / Block statics // Currently there is nothing to check for paths return emptyErrs(); }; const checkLine = ( selEnv: SelEnv, line: Stmt, acc: StyleResults ): StyleResults => { if (line.tag === "PathAssign") { const pErrs = checkBlockPath(selEnv, line.path); const eErrs = checkBlockExpr(selEnv, line.value); return combineErrs(combineErrs(acc, pErrs), eErrs); } else if (line.tag === "Override") { const pErrs = checkBlockPath(selEnv, line.path); const eErrs = checkBlockExpr(selEnv, line.value); return combineErrs(combineErrs(acc, pErrs), eErrs); } else if (line.tag === "Delete") { const pErrs = checkBlockPath(selEnv, line.contents); return combineErrs(acc, pErrs); } else { throw Error( "Case should not be reached (anonymous statement should be substituted for a local one in `nameAnonStatements`)" ); } }; const checkBlock = (selEnv: SelEnv, block: Block): StyleErrors => { // Block checking; static semantics // The below properties are checked in one pass (a fold) over the Style AST: // Check that every shape name and shape property name in a shape constructor exists // Check that every function, objective, and constraint exists // NOT CHECKED as this requires more advanced env-building work: At path construction time, check that every Substance object exists in the environment of the block + selector, or that it's defined as a local variable const res: StyleResults = block.statements.reduce( (acc: StyleResults, stmt: Stmt): StyleResults => checkLine(selEnv, stmt, acc), emptyErrs() ); // TODO(errors): Return warnings (non-fatally); currently there are no warnings though if (res.warnings.length > 0) { console.error("warnings", res.warnings); throw Error("Internal error: report these warnings"); } return res.errors; }; //#endregion Block statics // Judgment 23, contd. const translatePair = ( varEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, trans: Translation, hb: HeaderBlock, blockNum: number ): Either<StyleErrors, Translation> => { if (hb.header.tag === "Namespace") { const selEnv = initSelEnv(); const bErrs = checkBlock(selEnv, hb.block); // TODO: block statics if (selEnv.errors.length > 0 || bErrs.length > 0) { // This is a namespace, not selector, so we substitute local vars with the namespace's name // skip transSubstsBlock; only one subst return { tag: "Left", contents: selEnv.errors.concat(bErrs), }; } const subst = {}; // COMBAK / errors: Keep the AST node from `hb.header` for error reporting? return translateBlock( { tag: "Just", contents: (hb.header.contents.contents.value as any) as string, }, [hb.block, blockNum], trans, [subst, 0] ); } else if (hb.header.tag === "Selector") { const selEnv = checkHeader(varEnv, hb.header); const bErrs = checkBlock(selEnv, hb.block); // TODO: block statics // If any Substance variable in the selector environment doesn't exist in the Substance program (e.g. Set `A`), // skip this block (because the Substance variable won't exist in the translation) if (selEnv.skipBlock) { return toRight(trans); } if (selEnv.errors.length > 0 || bErrs.length > 0) { return { tag: "Left", contents: selEnv.errors.concat(bErrs), }; } // For creating unique local var names const substs = findSubstsSel(varEnv, subEnv, subProg, [hb.header, selEnv]); return translateSubstsBlock(trans, numbered(substs), [hb.block, blockNum]); } else throw Error("unknown tag"); }; // Map a function over the translation const mapTrans = ( trans: Translation, f: (name: string, fieldDict: FieldDict) => [string, FieldDict] ): Translation => { return { ...trans, trMap: Object.fromEntries( Object.entries(trans.trMap).map(([n, fd]) => f(n, fd)) ), }; }; // Note, this mutates the translation const insertNames = (trans: Translation): Translation => { const insertName = ( name: string, fieldDict: FieldDict ): [string, FieldDict] => { fieldDict.name = { tag: "FExpr", contents: { tag: "Done", contents: { tag: "StrV", contents: name }, }, }; return [name, fieldDict]; }; return mapTrans(trans, insertName); }; /** * Add label strings to the translation, regardless if the Substance object is selected in the Style program * NOTE: this function mutates `trans`. * * @param trans `Translation` without labels * @param labels the label map from the Substance compiler */ const insertLabels = (trans: Translation, labels: LabelMap): void => { for (const labelData of labels) { const [name, label] = labelData; if (label.isJust()) { const labelString = label.value; const labelValue: TagExpr<VarAD> = { tag: "Done", contents: { tag: "StrV", contents: labelString, }, }; const labelExpr: FieldExpr<VarAD> = { tag: "FExpr", contents: labelValue, }; const fieldDict = trans.trMap[name]; if (fieldDict !== undefined) { fieldDict[LABEL_FIELD] = labelExpr; } else { trans[name] = { [LABEL_FIELD]: labelExpr, }; } } } }; const translateStyProg = ( varEnv: Env, subEnv: SubstanceEnv, subProg: SubProg, styProg: StyProg, labelMap: LabelMap, styVals: number[] ): Either<StyleErrors, Translation> => { // COMBAK: Deal with styVals const res = foldM( styProg.blocks, (trans, hb, i) => translatePair(varEnv, subEnv, subProg, trans, hb, i), initTrans() ); if (isLeft(res)) { return res; } // Return errors const trans = res.contents; const transWithNames = insertNames(trans); insertLabels(transWithNames, labelMap); // NOTE: mutates `transWithNames` // COMBAK: Do this with plugins // const styValMap = styJsonToMap(styVals); // const transWithPlugins = evalPluginAccess(styValMap, transWithNamesAndLabels); // return Right(transWithPlugins); return toRight(transWithNames); }; //#endregion // BEGIN GENOPTPROBLEM.HS PORT //#region Translation utilities -- TODO move to EngineUtils function foldFields<T>( f: (s: string, field: Field, fexpr: FieldExpr<VarAD>, acc: T[]) => T[], [name, fieldDict]: [string, { [k: string]: FieldExpr<VarAD> }], acc: T[] ): T[] { const res: T[] = Object.entries(fieldDict).reduce( (acc: T[], [field, expr]) => f(name, field, expr, acc), [] ); return res.concat(acc); } function foldSubObjs<T>( f: (s: string, f: Field, fexpr: FieldExpr<VarAD>, acc: T[]) => T[], tr: Translation ): T[] { return Object.entries(tr.trMap).reduce( (acc: T[], curr) => foldFields(f, curr, acc), [] ); } //#endregion //#region Gen opt problem // Find varying (float) paths // For now, don't optimize these float-valued properties of a GPI // (use whatever they are initialized to in Shapes or set to in Style) const unoptimizedFloatProperties: string[] = [ "rotation", "strokeWidth", "thickness", "transform", "transformation", "opacity", "finalW", "finalH", "arrowheadSize", ]; const optimizedVectorProperties: string[] = ["start", "end", "center"]; const declaredVarying = (t: TagExpr<VarAD>): boolean => { if (t.tag === "OptEval") { return isVarying(t.contents); } return false; }; const mkPath = (strs: string[]): Path => { if (strs.length === 2) { const [name, field] = strs; return { tag: "FieldPath", nodeType: "SyntheticStyle", children: [], name: { nodeType: "SyntheticStyle", children: [], tag: "SubVar", contents: { ...dummyId(name), }, }, field: dummyId(field), }; } else if (strs.length === 3) { const [name, field, prop] = strs; return { tag: "PropertyPath", nodeType: "SyntheticStyle", children: [], name: { nodeType: "SyntheticStyle", children: [], tag: "SubVar", contents: { ...dummyId(name), }, }, field: dummyId(field), property: dummyId(prop), }; } else throw Error("bad # inputs"); }; const pendingProperties = (s: ShapeTypeStr): PropID[] => { if (s === "Text") return ["w", "h"]; if (s === "TextTransform") return ["w", "h"]; if (s === "ImageTransform") return ["initWidth", "initHeight"]; return []; }; const isVarying = (e: Expr): boolean => { return e.tag === "Vary" || e.tag === "VaryInit"; }; const isPending = (s: ShapeTypeStr, p: PropID): boolean => { return pendingProperties(s).includes(p); }; // ---- FINDING VARIOUS THINGS IN THE TRANSLATION const findPropertyVarying = ( name: string, field: Field, properties: { [k: string]: TagExpr<VarAD> }, floatProperty: string, acc: Path[] ): Path[] => { const expr = properties[floatProperty]; const path = mkPath([name, field, floatProperty]); if (!expr) { if (unoptimizedFloatProperties.includes(floatProperty)) { return acc; } if (optimizedVectorProperties.includes(floatProperty)) { const defaultVec2: TagExpr<VarAD> = { tag: "OptEval", contents: { nodeType: "SyntheticStyle", children: [], tag: "Vector", contents: [ dummyASTNode({ tag: "Vary" }, "SyntheticStyle") as Expr, dummyASTNode({ tag: "Vary" }, "SyntheticStyle") as Expr, ], }, }; // Return paths for both elements, COMBAK: This hardcodes that unset vectors have 2 elements, need to generalize const paths = findNestedVarying(defaultVec2, path); return paths.concat(acc); } return [path].concat(acc); } else { if (declaredVarying(expr)) { return [path].concat(acc); } } const paths = findNestedVarying(expr, path); return paths.concat(acc); }; // Look for nested varying variables, given the path to its parent var (e.g. `x.r` => (-1.2, ?)) => `x.r`[1] is varying const findNestedVarying = (e: TagExpr<VarAD>, p: Path): Path[] => { if (e.tag === "OptEval") { const res = e.contents; if (res.tag === "Vector") { const elems: Expr[] = res.contents; const indices: Path[] = elems .map((e: Expr, i): [Expr, number] => [e, i]) .filter((e: [Expr, number]): boolean => isVarying(e[0])) .map( ([e, i]: [Expr, number]): IAccessPath => ({ nodeType: "SyntheticStyle", children: [], tag: "AccessPath", path: p, indices: [ dummyASTNode({ tag: "Fix", contents: i }, "SyntheticStyle"), ], } as IAccessPath) ); return indices; } else if ( res.tag === "Matrix" || res.tag === "List" || res.tag === "Tuple" ) { // COMBAK: This should search, but for now we just don't handle nested varying vars in these return []; } } return []; }; // Given 'propType' and 'shapeType', return all props of that ValueType // COMBAK: Model "FloatT", "FloatV", etc as types for ValueType const propertiesOf = (propType: string, shapeType: ShapeTypeStr): PropID[] => { const shapeInfo: [string, [PropType, Sampler]][] = Object.entries( findDef(shapeType).properties ); return shapeInfo .filter(([pName, [pType, s]]) => pType === propType) .map((e) => e[0]); }; // Given 'propType' and 'shapeType', return all props NOT of that ValueType const propertiesNotOf = ( propType: string, shapeType: ShapeTypeStr ): PropID[] => { const shapeInfo: [string, [PropType, Sampler]][] = Object.entries( findDef(shapeType).properties ); return shapeInfo .filter(([pName, [pType, s]]) => pType !== propType) .map((e) => e[0]); }; // Find varying fields const findFieldVarying = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Path[] ): Path[] => { if (fexpr.tag === "FExpr") { if (declaredVarying(fexpr.contents)) { return [mkPath([name, field])].concat(acc); } const paths = findNestedVarying(fexpr.contents, mkPath([name, field])); return paths.concat(acc); } else if (fexpr.tag === "FGPI") { const [typ, properties] = fexpr.contents; const ctorFloats = propertiesOf("FloatV", typ).concat( propertiesOf("VectorV", typ) ); const varyingFloats = ctorFloats.filter((e) => !isPending(typ, e)); // This splits up vector-typed properties into one path for each element const vs: Path[] = varyingFloats.reduce( (acc: Path[], curr) => findPropertyVarying(name, field, properties, curr, acc), [] ); return vs.concat(acc); } else throw Error("unknown tag"); }; // Find all varying paths const findVarying = (tr: Translation): Path[] => { return foldSubObjs(findFieldVarying, tr); }; // Find uninitialized (non-float) property paths const findPropertyUninitialized = ( name: string, field: Field, properties: GPIMap, nonfloatProperty: string, acc: Path[] ): Path[] => { // nonfloatProperty is a non-float property that is NOT set by the user and thus we can sample it const res = properties[nonfloatProperty]; if (!res) { return [mkPath([name, field, nonfloatProperty])].concat(acc); } return acc; }; // Find uninitialized fields const findFieldUninitialized = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Path[] ): Path[] => { // NOTE: we don't find uninitialized field because you can't leave them uninitialized. Plus, we don't know what types they are if (fexpr.tag === "FExpr") { return acc; } if (fexpr.tag === "FGPI") { const [typ, properties] = fexpr.contents; const ctorNonfloats = propertiesNotOf("FloatV", typ).filter( (e) => e !== "name" ); const uninitializedProps = ctorNonfloats; const vs = uninitializedProps.reduce( (acc: Path[], curr) => findPropertyUninitialized(name, field, properties, curr, acc), [] ); return vs.concat(acc); } throw Error("unknown tag"); }; // NOTE: we don't find uninitialized field because you can't leave them uninitialized. Plus, we don't know what types they are const findUninitialized = (tr: Translation): Path[] => { return foldSubObjs(findFieldUninitialized, tr); }; // Fold function to return the names of GPIs const findGPIName = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: [string, Field][] ): [string, Field][] => { if (fexpr.tag === "FGPI") { return ([[name, field]] as [string, Field][]).concat(acc); } else if (fexpr.tag === "FExpr") { return acc; } else throw Error("unknown tag"); }; // Find shapes and their properties const findShapeNames = (tr: Translation): [string, string][] => { return foldSubObjs(findGPIName, tr); }; // Find paths that are the properties of shapes const findShapeProperties = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: [string, Field, Property][] ): [string, Field, Property][] => { if (fexpr.tag === "FGPI") { const properties = fexpr.contents[1]; const paths = Object.keys(properties).map( (property) => [name, field, property] as [string, Field, Property] ); return paths.concat(acc); } else if (fexpr.tag === "FExpr") { return acc; } else throw Error("unknown tag"); }; // Find paths that are the properties of shapes const findShapesProperties = (tr: Translation): [string, string, string][] => { return foldSubObjs(findShapeProperties, tr); }; // Find various kinds of functions const findFieldFns = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Either<StyleOptFn, StyleOptFn>[] ): Either<StyleOptFn, StyleOptFn>[] => { if (fexpr.tag === "FExpr") { if (fexpr.contents.tag === "OptEval") { const e = fexpr.contents.contents; // COMBAK: This throws away the function's Identifier for future debugging // (Also, why doesn't typescript report an error when `e.name` is an Identifier but a StyleOptFn expects a string, using the `as` keyword?) if (e.tag === "ObjFn") { const res: Either<StyleOptFn, StyleOptFn> = ToLeft([ e.name.value, e.args, ]); return [res].concat(acc); } else if (e.tag === "ConstrFn") { const res: Either<StyleOptFn, StyleOptFn> = ToRight([ e.name.value, e.args, ]); return [res].concat(acc); } else { return acc; } } } return acc; }; // Ported from `findObjfnsConstrs` const findUserAppliedFns = (tr: Translation): [Fn[], Fn[]] => { return convertFns(foldSubObjs(findFieldFns, tr)); }; const findFieldDefaultFns = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Either<StyleOptFn, StyleOptFn>[] ): Either<StyleOptFn, StyleOptFn>[] => { // TODO < Currently we have no default objectives/constraints, so it's not implemented return []; }; const findDefaultFns = (tr: Translation): [Fn[], Fn[]] => { return convertFns(foldSubObjs(findFieldDefaultFns, tr)); }; const toFn = (t: OptType, [name, args]: StyleOptFn): Fn => { return { fname: name, fargs: args, optType: t, }; }; const toFns = ([objfns, constrfns]: [StyleOptFn[], StyleOptFn[]]): [ Fn[], Fn[] ] => { return [ objfns.map((fn) => toFn("ObjFn", fn)), constrfns.map((fn) => toFn("ConstrFn", fn)), ]; }; // COMBAK: Move this to utils function partitionEithers<A, B>(es: Either<A, B>[]): [A[], B[]] { return [ es.filter((e) => e.tag === "Left").map((e) => e.contents as A), es.filter((e) => e.tag === "Right").map((e) => e.contents as B), ]; } const convertFns = (fns: Either<StyleOptFn, StyleOptFn>[]): [Fn[], Fn[]] => { return toFns(partitionEithers(fns)); }; // Extract number from a more complicated type // also ported from `lookupPaths` const getNum = (e: TagExpr<VarAD> | IFGPI<VarAD>): number => { if (e.tag === "OptEval") { if (e.contents.tag === "Fix") { return e.contents.contents; } if (e.contents.tag === "VaryAD") { return e.contents.contents.val; } else { throw Error("internal error: invalid varying path"); } } else if (e.tag === "Done") { if (e.contents.tag === "FloatV") { return numOf(e.contents.contents); } else { throw Error("internal error: invalid varying path"); } } else if (e.tag === "Pending") { throw Error("internal error: invalid varying path"); } else if (e.tag === "FGPI") { throw Error("internal error: invalid varying path"); } else { throw Error("internal error: unknown tag"); } }; // ported from `lookupPaths` // lookup paths with the expectation that each one is a float export const lookupNumericPaths = (ps: Path[], tr: Translation): number[] => { return ps.map((path) => findExprSafe(tr, path)).map(getNum); }; const findFieldPending = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Path[] ): Path[] => { if (fexpr.tag === "FExpr") { return acc; } else if (fexpr.tag === "FGPI") { const properties = fexpr.contents[1]; const pendingProps = Object.entries(properties) .filter(([k, v]) => v.tag === "Pending") .map((e: [string, TagExpr<VarAD>]) => e[0]); // TODO: Pending properties currently don't support AccessPaths return pendingProps .map((property) => mkPath([name, field, property])) .concat(acc); } else throw Error("unknown tag"); }; // Find pending paths // Find the paths to all pending, non-float, non-name properties const findPending = (tr: Translation): Path[] => { return foldSubObjs(findFieldPending, tr); }; // ---- INITIALIZATION const isFieldOrAccessPath = (p: Path): boolean => { if (p.tag === "FieldPath") { return true; } else if (p.tag === "AccessPath") { if (p.path.tag === "FieldPath" || p.path.tag === "PropertyPath") { return true; } else throw Error("unexpected sub-accesspath type"); } return false; }; // sample varying fields only (from the range defined by canvas dims) and store them in the translation // example: A.val = OPTIMIZED // This also samples varying access paths, e.g. // Circle { center : (1.1, ?) ... } <// the latter is an access path that gets initialized here // varying init paths are separated out and initialized with the value specified by the style writer // NOTE: Mutates translation const initFieldsAndAccessPaths = ( varyingPaths: Path[], tr: Translation ): Translation => { const varyingFieldsAndAccessPaths = varyingPaths.filter(isFieldOrAccessPath); const canvas = getCanvas(tr); const initVals = varyingFieldsAndAccessPaths.map( (p: Path): TagExpr<VarAD> => { // by default, sample randomly in canvas X range let initVal = randFloat(...canvas.xRange); // unless it's a VaryInit, in which case, don't sample, set to the init value // TODO: This could technically use `varyingInitPathsAndVals`? const res = findExpr(tr, p); // Some varying paths may not be in the translation. That's OK. if (res.tag === "OptEval") { if (res.contents.tag === "VaryInit") { initVal = res.contents.contents; } } return { tag: "Done", contents: { tag: "FloatV", contents: constOf(initVal), }, }; } ); const tr2 = insertExprs( varyingFieldsAndAccessPaths, initVals, tr, false, true ); return tr2; }; // //////////// Generating an initial state (concrete values for all fields/properties needed to draw the GPIs) // 1. Initialize all varying fields // 2. Initialize all properties of all GPIs // NOTE: since we store all varying paths separately, it is okay to mark the default values as Done // they will still be optimized, if needed. // TODO: document the logic here (e.g. only sampling varying floats) and think about whether to use translation here or [Shape a] since we will expose the sampler to users later // TODO: Doesn't sample partial shape properties, like start: (?, 1.) <- this is actually sampled by initFieldsAndAccessPaths // NOTE: Shape properties are mutated; they are returned as a courtesy const initProperty = ( shapeType: ShapeTypeStr, properties: GPIProps<VarAD>, [propName, [propType, propSampler]]: [string, [PropType, Sampler]], canvas: Canvas ): GPIProps<VarAD> => { const propVal: Value<number> = propSampler(canvas); const propValAD: Value<VarAD> = valueNumberToAutodiffConst(propVal); const propValDone: TagExpr<VarAD> = { tag: "Done", contents: propValAD }; const styleSetting: TagExpr<VarAD> = properties[propName]; // Property not set in Style if (!styleSetting) { if (isPending(shapeType, propName)) { properties[propName] = { tag: "Pending", contents: propValAD, } as TagExpr<VarAD>; return properties; } else { properties[propName] = propValDone; // Use the sampled one return properties; } } // Property set in Style if (styleSetting.tag === "OptEval") { if (styleSetting.contents.tag === "Vary") { properties[propName] = propValDone; // X.prop = ? return properties; } else if (styleSetting.contents.tag === "VaryInit") { // Initialize the varying variable to the property specified in Style properties[propName] = { tag: "Done", contents: { tag: "FloatV", contents: varOf(styleSetting.contents.contents), }, }; return properties; } else if (styleSetting.contents.tag === "Vector") { const v: Expr[] = styleSetting.contents.contents; if (v.length === 2) { // Sample a whole 2D vector, e.g. `Circle { center : [?, ?] }` // (if only one element is set to ?, then presumably it's set by initializing an access path...? TODO: Check this) // TODO: This hardcodes an uninitialized 2D vector to be initialized/inserted if (v[0].tag === "Vary" && v[1].tag === "Vary") { properties[propName] = propValDone; return properties; } } return properties; } else { return properties; } } else if (styleSetting.tag === "Done") { // TODO: pending properties are only marked if the Style source does not set them explicitly // Check if this is the right decision. We still give pending values a default such that the initial list of shapes can be generated without errors. return properties; } throw Error("internal error: unknown tag or invalid value for property"); }; const mkShapeName = (s: string, f: Field): string => { return `${s}.${f}`; }; // COMBAK: This will require `getNames` to work const initShape = ( tr: Translation, [n, field]: [string, Field] ): Translation => { const path = mkPath([n, field]); const res = findExprSafe(tr, path); // This is safe (as used in GenOptProblem) since we only initialize shapes with paths from the translation if (res.tag === "FGPI") { const [stype, props] = res.contents as [string, GPIProps<VarAD>]; const def: ShapeDef = findDef(stype); const gpiTemplate: [string, [PropType, Sampler]][] = Object.entries( def.properties ); const instantiatedGPIProps: GPIProps<VarAD> = gpiTemplate.reduce( ( newGPI: GPIProps<VarAD>, propTemplate: [string, [PropType, Sampler]] ): GPIProps<VarAD> => initProperty(stype, newGPI, propTemplate, getCanvas(tr)), clone(props) ); // NOTE: `initProperty` mutates its input, so the `props` from the translation is cloned here, so the one in the translation itself isn't mutated // Insert the name of the shape into its prop dict // NOTE: getShapes resolves the names + we don't use the names of the shapes in the translation // The name-adding logic can be removed but is left in for debugging const shapeName = mkShapeName(n, field); instantiatedGPIProps.name = { tag: "Done", contents: { tag: "StrV", contents: shapeName, }, }; const gpi: IFGPI<VarAD> = { tag: "FGPI", contents: [stype, instantiatedGPIProps], }; return insertGPI(path, gpi, tr); } else throw Error("expected GPI but got field"); }; const initShapes = (tr: Translation, pths: [string, string][]): Translation => { return pths.reduce(initShape, tr); }; //#region layering const findLayeringExpr = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Expr[] ): Expr[] => { if (fexpr.tag === "FExpr") { if (fexpr.contents.tag === "OptEval") { if (fexpr.contents.contents.tag === "Layering") { const layering: ILayering = fexpr.contents.contents; return [layering as Expr].concat(acc); } } } return acc; }; const findLayeringExprs = (tr: Translation): Expr[] => { return foldSubObjs(findLayeringExpr, tr); }; const lookupGPIName = (p: Path, tr: Translation): string => { if (p.tag === "FieldPath") { // COMBAK: Deal with path synonyms / aliases by looking them up? return getShapeName(p.name.contents.value, p.field.value); } else { throw Error("expected path to GPI"); } }; const findNames = (e: Expr, tr: Translation): [string, string] => { if (e.tag === "Layering") { return [lookupGPIName(e.below, tr), lookupGPIName(e.above, tr)]; } else { throw Error("unknown tag"); } }; const topSortLayering = ( allGPINames: string[], partialOrderings: [string, string][] ): MaybeVal<string[]> => { const layerGraph: Graph = new Graph(); allGPINames.map((name: string) => layerGraph.setNode(name)); // topsort will return the most upstream node first. Since `shapeOrdering` is consistent with the SVG drawing order, we assign edges as "below => above". partialOrderings.map(([below, above]: [string, string]) => layerGraph.setEdge(below, above) ); try { const globalOrdering: string[] = alg.topsort(layerGraph); return { tag: "Just", contents: globalOrdering }; } catch (e) { return { tag: "Nothing" }; } }; const computeShapeOrdering = (tr: Translation): string[] => { const layeringExprs = findLayeringExprs(tr); // Returns list of layering specifications [below, above] const partialOrderings: [string, string][] = layeringExprs.map((e: Expr): [ string, string ] => findNames(e, tr)); const allGPINames: string[] = findShapeNames( tr ).map((e: [string, Field]): string => getShapeName(e[0], e[1])); const shapeOrdering = topSortLayering(allGPINames, partialOrderings); // TODO: Errors for labeling if (shapeOrdering.tag === "Nothing") { throw Error("no shape ordering possible from layering"); } return shapeOrdering.contents; }; //#endregion const isVaryingInitPath = ( p: Path, tr: Translation ): [Path, MaybeVal<number>] => { const res = findExpr(tr, p); // Some varying paths may not be in the translation. That's OK. if (res.tag === "OptEval") { if (res.contents.tag === "VaryInit") { return [p, { tag: "Just", contents: res.contents.contents }]; } } return [p, { tag: "Nothing" }]; }; // ---- MAIN FUNCTION // COMBAK: Add optConfig as param? const genState = (trans: Translation): Result<State, StyleErrors> => { const varyingPaths = findVarying(trans); // NOTE: the properties in uninitializedPaths are NOT floats. Floats are included in varyingPaths already const varyingInitPathsAndVals: [Path, number][] = (varyingPaths .map((p) => isVaryingInitPath(p, trans)) .filter( (tup: [Path, MaybeVal<number>]): boolean => tup[1].tag === "Just" ) as [Path, Just<number>][]) // TODO: Not sure how to get typescript to understand `filter`... .map((tup: [Path, Just<number>]) => [tup[0], tup[1].contents]); const varyingInitInfo: { [pathStr: string]: number } = Object.fromEntries( varyingInitPathsAndVals.map((e) => [prettyPrintPath(e[0]), e[1]]) ); const uninitializedPaths = findUninitialized(trans); const shapePathList: [string, string][] = findShapeNames(trans); const shapePaths = shapePathList.map(mkPath); const canvasErrs = checkCanvas(trans); if (canvasErrs.length > 0) { return err(canvasErrs); } // sample varying vals and instantiate all the non - float base properties of every GPI in the translation // this has to be done before `initFieldsAndAccessPaths` as AccessPaths may depend on shapes' properties already having been initialized const transInitShapes = initShapes(trans, shapePathList); // sample varying fields and access paths, and put them in the translation const transInitAll = initFieldsAndAccessPaths(varyingPaths, transInitShapes); // CHECK TRANSLATION // Have to check it after the shapes are initialized, otherwise it will complain about uninitialized shape paths const transErrs = checkTranslation(transInitAll); if (transErrs.length > 0) { return err(transErrs); } const shapeProperties = findShapesProperties(transInitAll); const [objfnsDecl, constrfnsDecl] = findUserAppliedFns(transInitAll); const [objfnsDefault, constrfnsDefault] = findDefaultFns(transInitAll); const [objFns, constrFns] = [ objfnsDecl.concat(objfnsDefault), constrfnsDecl.concat(constrfnsDefault), ]; const [initialGPIs, transEvaled] = [[], transInitAll]; const initVaryingState: number[] = lookupNumericPaths( varyingPaths, transEvaled ); const pendingPaths = findPending(transInitAll); const shapeOrdering = computeShapeOrdering(transInitAll); // deal with layering const initState = { shapes: initialGPIs, // These start out empty because they are initialized in the frontend via `evalShapes` in the Evaluator shapePaths, shapeProperties, shapeOrdering, translation: transInitAll, // This is the result of the data processing originalTranslation: clone(trans), varyingPaths, varyingValues: initVaryingState, varyingInitInfo, uninitializedPaths, pendingPaths, objFns, constrFns, // `params` are initialized properly by optimization; the only thing it needs is the weight (for the objective function synthesis) params: ({ optStatus: "NewIter" as const, weight: initConstraintWeight, lbfgsInfo: defaultLbfgsParams, UOround: -1, EPround: -1, } as unknown) as Params, labelCache: [], rng: undefined as any, policyParams: undefined as any, oConfig: undefined as any, selectorMatches: undefined as any, varyingMap: {} as any, // TODO: Should this be empty? canvas: getCanvas(trans), }; return ok(initState); }; //#endregion export const parseStyle = (p: string): Result<StyProg, ParseError> => { const parser = new nearley.Parser(nearley.Grammar.fromCompiled(styleGrammar)); try { const { results } = parser.feed(p).feed("\n"); if (results.length > 0) { const ast: StyProg = results[0] as StyProg; return ok(ast); } else { return err(parseError(`Unexpected end of input`, lastLocation(parser))); } } catch (e) { return err(parseError(e, lastLocation(parser))); } }; //#region Checking translation const isStyErr = (res: TagExpr<VarAD> | IFGPI<VarAD> | StyleError): boolean => res.tag !== "FGPI" && !isTagExpr(res); const findPathsExpr = (expr: Expr): Path[] => { // TODO: Factor the expression-folding pattern out from here and `checkBlockExpr` if (isPath(expr)) { return [expr]; } else if ( expr.tag === "CompApp" || expr.tag === "ObjFn" || expr.tag === "ConstrFn" ) { return _.flatMap(expr.args, findPathsExpr); } else if (expr.tag === "BinOp") { return _.flatMap([expr.left, expr.right], findPathsExpr); } else if (expr.tag === "UOp") { return findPathsExpr(expr.arg); } else if ( expr.tag === "List" || expr.tag === "Vector" || expr.tag === "Matrix" ) { return _.flatMap(expr.contents, findPathsExpr); } else if (expr.tag === "ListAccess") { return [expr.contents[0]]; } else if (expr.tag === "GPIDecl") { return _.flatMap( expr.properties.map((p) => p.value), findPathsExpr ); } else if (expr.tag === "Layering") { return [expr.below, expr.above]; } else if (expr.tag === "PluginAccess") { return _.flatMap([expr.contents[1], expr.contents[2]], findPathsExpr); } else if (expr.tag === "Tuple") { return _.flatMap([expr.contents[0], expr.contents[1]], findPathsExpr); } else if (expr.tag === "VectorAccess") { return [expr.contents[0]].concat(findPathsExpr(expr.contents[1])); } else if (expr.tag === "MatrixAccess") { return [expr.contents[0]].concat( _.flatMap(expr.contents[1], findPathsExpr) ); } else if ( expr.tag === "Fix" || expr.tag === "Vary" || expr.tag === "VaryInit" || expr.tag === "VaryAD" || expr.tag === "StringLit" || expr.tag === "BoolLit" ) { return []; } else { console.error("expr", expr); throw Error("unknown tag"); } }; // Find all paths given explicitly anywhere in an expression in the translation. // (e.g. `x.shape above y.shape` <-- return [`x.shape`, `y.shape`]) const findPathsField = ( name: string, field: Field, fexpr: FieldExpr<VarAD>, acc: Path[] ): Path[] => { if (fexpr.tag === "FExpr") { // Only look deeper in expressions, because that's where paths might be if (fexpr.contents.tag === "OptEval") { const res: Path[] = findPathsExpr(fexpr.contents.contents); return acc.concat(res); } else { return acc; } } else if (fexpr.tag === "FGPI") { // Get any exprs that the properties are set to const propExprs: Expr[] = Object.entries(fexpr.contents[1]) .map((e) => e[1]) .filter((e: TagExpr<VarAD>): boolean => e.tag === "OptEval") .map((e) => e as IOptEval<VarAD>) // Have to cast because TypeScript doesn't know the type changed from the filter above .map((e: IOptEval<VarAD>): Expr => e.contents); const res: Path[] = _.flatMap(propExprs, findPathsExpr); return acc.concat(res); } throw Error("unknown tag"); }; // Check that canvas dimensions exist and have the proper type. const checkCanvas = (tr: Translation): StyleErrors => { let errs: StyleErrors = []; if (!("canvas" in tr.trMap)) { errs.push({ tag: "CanvasNonexistentError", }); return errs; } if (!("width" in tr.trMap.canvas)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "width", kind: "missing", }); } else if (!("contents" in tr.trMap.canvas.width.contents)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "width", kind: "GPI", }); } else if (!("contents" in tr.trMap.canvas.width.contents.contents)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "width", kind: "uninitialized", }); } else if ( typeof tr.trMap.canvas.width.contents.contents.contents !== "number" ) { const val = tr.trMap.canvas.width.contents.contents; let type; if (typeof val === "object" && "tag" in val) { type = val.tag; } else { type = typeof val; } errs.push({ tag: "CanvasNonexistentDimsError", attr: "width", kind: "wrong type", type, }); } if (!("height" in tr.trMap.canvas)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "height", kind: "missing", }); } else if (!("contents" in tr.trMap.canvas.height.contents)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "height", kind: "GPI", }); } else if (!("contents" in tr.trMap.canvas.height.contents.contents)) { errs.push({ tag: "CanvasNonexistentDimsError", attr: "height", kind: "uninitialized", }); } else if ( typeof tr.trMap.canvas.height.contents.contents.contents !== "number" ) { const val = tr.trMap.canvas.height.contents.contents; let type; if (typeof val === "object" && "tag" in val) { type = val.tag; } else { type = typeof val; } errs.push({ tag: "CanvasNonexistentDimsError", attr: "height", kind: "wrong type", type, }); } return errs; }; // Check translation integrity const checkTranslation = (trans: Translation): StyleErrors => { // Look up all paths used anywhere in the translation's expressions and verify they exist in the translation const allPaths: Path[] = foldSubObjs(findPathsField, trans); const allPathsUniq: Path[] = _.uniqBy(allPaths, prettyPrintPath); const exprs = allPathsUniq.map((p) => findExpr(trans, p)); const errs = exprs.filter(isStyErr); return errs as StyleErrors; // Should be true due to the filter above, though you can't use booleans and the `res is StyleError` assertion together. }; //#endregion Checking translation /* Precondition: checkCanvas returns without error */ export const getCanvas = (tr: Translation): Canvas => { let width = ((tr.trMap.canvas.width.contents as TagExpr<VarAD>) .contents as Value<VarAD>).contents as number; let height = ((tr.trMap.canvas.height.contents as TagExpr<VarAD>) .contents as Value<VarAD>).contents as number; return { width, height, size: [width, height], xRange: [-width / 2, width / 2], yRange: [-height / 2, height / 2], }; }; export const compileStyle = ( stySource: string, subEnv: SubstanceEnv, varEnv: Env ): Result<State, PenroseError> => { const subProg = subEnv.ast; const astOk = parseStyle(stySource); let styProgInit; if (astOk.isOk()) { styProgInit = astOk.value; } else { return err({ ...astOk.error, errorType: "StyleError" }); } const labelMap = subEnv.labels; // Name anon statements const styProg: StyProg = nameAnonStatements(styProgInit); log.info("old prog", styProgInit); log.info("new prog, with named anon statements", styProg); // Check selectors; return list of selector environments (`checkSels`) const selEnvs = checkSelsAndMakeEnv(varEnv, styProg.blocks); // TODO(errors/warn): distinguish between errors and warnings const selErrs: StyleErrors = _.flatMap(selEnvs, (e) => e.warnings.concat(e.errors) ); if (selErrs.length > 0) { // TODO(errors): Report all of them, not just the first? return err(toStyleErrors(selErrs)); } // Leaving these logs in because they are still useful for debugging, but TODO: remove them log.info("selEnvs", selEnvs); // Find substitutions (`find_substs_prog`) const subss = findSubstsProg( varEnv, subEnv, subProg, styProg.blocks, selEnvs ); // TODO: Use `eqEnv` // TODO: I guess `subss` is not actually used? remove? log.info("substitutions", subss); // Translate style program const styVals: number[] = []; // COMBAK: Deal with style values when we have plugins const translateRes = translateStyProg( varEnv, subEnv, subProg, styProg, labelMap, styVals ); log.info("translation (before genOptProblem)", translateRes); // Translation failed somewhere if (translateRes.tag === "Left") { return err(toStyleErrors(translateRes.contents)); } const trans = translateRes.contents; if (trans.warnings.length > 0) { // TODO(errors): these errors are currently returned as warnings -- maybe systematize it log.info("Returning warnings as errors"); return err(toStyleErrors(trans.warnings)); } // TODO(errors): `findExprsSafe` shouldn't fail (as used in `genOptProblemAndState`, since all the paths are generated from the translation) but could always be safer... const initState: Result<State, StyleErrors> = genState(trans); log.info("init state from GenOptProblem", initState); if (initState.isErr()) { return err(toStyleErrors(initState.error)); } return ok(initState.value); };
the_stack